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
,p
would associate to2
andx
s from[3..]
. - Next, in the list comprehension
x<-3
, but then how can we call sieve with just3
when 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
sieve
once:First,
x
gets value3
which passes themod 2
filterInline
sieve
again (I renamedx
toy
to prevent confusions)Now
x = 4
fails themod 2
filter butx = 5
passes it. SoThis
y = 5
also passes themod 3
filter so now we haveExpanding
sieve
one more time (z
instead ofy
) gets us toAnd the expansion continues on the same way.