Reputation: 81
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]
[[2,2,4],[2,4,6,8],[2,4,2,6,2,6]]
This piece of code relates to list comprehension. But i don't see how the program goes with "even"
Upvotes: 1
Views: 58
Reputation: 476659
A Haskell list comprehension expression has three types of elements at the right side of the list comprehension:
var <- list-expr
;bool-expr
; andlet 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.
Upvotes: 7