basti12354
basti12354

Reputation: 2520

Filter at the list comprehension in haskell

I have this list comprehension:

[(x,y)| x<-[1..2], y<-[x..3], let z = x+y, odd z]
  1. The right result is [(1,2),(2,3)], but I can't understand why. What is the filter "let z = x+y, odd z" doing? There is no "z" in the other code, so I can't understand why this is changing something.
  2. Can somebody explain, step by step, what happens here.

Thanks a lot!

Upvotes: 6

Views: 6431

Answers (2)

Mark Karpov
Mark Karpov

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

Reed Oei
Reed Oei

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

Related Questions