Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 617
basti12354 Avatar asked Sep 18 '14 13:09

basti12354


People also ask

What are list comprehensions in Haskell?

List comprehension in Haskell is a way to produce the list of new elements from the generator we have passed inside it. Also for the generator values, we can apply the Haskell functions to modify it later. This list comprehension is very y easy to use and handle for developers and beginners as well.

Which is faster list comprehension or filter?

1 Answer. Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier.


1 Answers

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.

like image 67
Reed Oei Avatar answered Oct 09 '22 15:10

Reed Oei