Reputation: 578
In one of my courses I came across this:
numbers xs = [x | x<−xs , even x]
I understand that it takes a list of numbers and creates another list formed only with the even numbers from the original list. How exactly is it doing this? What does x<-xs
mean?
Upvotes: 2
Views: 3229
Reputation: 11238
As the other answers stated this a list comprehension notation, which means a way of defining a list in terms of another list. If you specify some predicates in the part after a |
, only elements satisfying these predicates will be taken, for example [x | x <- xs, even x]
is a list of all those elements x
taken from the list xs
that are even (meet the condition even x
). There can be more than one predicate:
[x | x <- xs, even x, x > 10]
You can also apply transformations to the drawn elements, including changing the list type:
λ> [x*2 | x <- [1 .. 20], even x, x > 10]
[24,28,32,36,40]
or:
λ> [show x | x <- [1 .. 20], even x, x > 10]
["12","14","16","18","20"]
Upvotes: 0
Reputation: 52008
This is a list comprehension where the notation is designed to be similar to set builder notation with the token <-
corresponding to the stylized lower case Greek epsilon which is the standard symbol for set membership. When I read list comprehensions I tend to read <-
as "drawn from", so I would parse [x | x<−xs , even x]
as "the list of all x such that x is drawn from xs and x is even" (,
corresponds to and
and is used to add conditions beyond mere membership in the list which is being drawn from).
Upvotes: 7