Reputation: 2520
I have this list comprehension:
[(x,y)| x<-[1..2], y<-[x..3], let z = x+y, odd z]
Thanks a lot!
Upvotes: 6
Views: 6431
Reputation: 7599
You're generating tuples, where sum of their elements must be an odd number. The line:
let z = x+y, odd z
gives name z
to the sum x + y
, this value then is used with predicate odd
to test if the sum is actually odd. Combinations of x
and y
, for which odd z
evaluates to True
get into the result list, others are removed.
Note that the lowest value for y
collection is actual value of variable x
:
x <- [1..2]
y <- [x..3]
This is to remove some 'duplicates' ((2,1)
) from consideration.
Upvotes: 5
Reputation: 1508
So x goes from 1 to 2, and y from x to 3.
So for the first one:
x = 1
y = 1
z = 1 + 1 = 2
z is not odd, therefore, it is not added. Then:
x = 1
y = 2
z = 1 + 2 = 3
z is now odd, so it is added. Then:
x = 1
y = 3
z = 1 + 3 = 4
z is even, ergo not added. Then:
x = 2
y = 2
z = 2 + 2 = 4
z is even.
Then:
x = 2
y = 3
z = 2 + 3 = 5
z is 5, odd, therefore added.
Upvotes: 6