ghci> let xxs=[[1,3,5,2,3,1,2,4,5],[1,2,3,4,5,6,7,8,9],[1,2,4,2,1,6,3,1,3,2,3,6]] 
ghci> [[x|x<-   xs,even x]|xs<- xxs]

This piece of code relates to list comprehension. But i don't see how the program goes with "even"

1 Answers

Willem Van Onsem On

A Haskell list comprehension expression has three types of elements at the right side of the list comprehension:

  1. generators, of the form var <- list-expr;
  2. filters of the form bool-expr; and
  3. local definitions of the form let var = expr.

The even x part is thus a filter. It means that only if the filter is satisfied, so even x results in True, that element is a candidate for the rest of the list comprehension and thus eventually result in a branch of elements added to the list.

So here the expression thus has two components:

[x | x <- xs, even x ]
--   \__ __/  \__ _/
--      v        v
--  generator  filter

we thus iterate over the elements in xs and then for each element check if that element is even, if it is, we add x to the result.

The above can however be written as just:

filter even xs

which basically describe what we do here: we filter a list xs such that the result is a list that only contains the elements of xs that are even.