I am a newbie to Haskell programming and have trouble understanding how the below list comprehension expands.
primes = sieve [2..]
sieve (p:xs) = p : sieve [x | x <-xs, x `mod` p /= 0]
Can someone correct me how the sieve expansion works:
- As we are pattern matching in
sieve,pwould associate to2andxs from[3..]. - Next, in the list comprehension
x<-3, but then how can we call sieve with just3when there is no short-circuit.
Other thing I do not understand is how recursion works here.
I think it would be clear if one could expand the above one step at a time for first few numbers, say until 5.
Let's do some equational reasoning.
The
[2..]is sintactic sugar for[2, 3, 4, 5, ...]soInline
sieveonce:First,
xgets value3which passes themod 2filterInline
sieveagain (I renamedxtoyto prevent confusions)Now
x = 4fails themod 2filter butx = 5passes it. SoThis
y = 5also passes themod 3filter so now we haveExpanding
sieveone more time (zinstead ofy) gets us toAnd the expansion continues on the same way.