I have trouble understanding this chunk of code:
let
sieve (p:xs) = p : sieve (filter (\ x -> x `mod` p /= 0) xs)
in sieve [2 .. ]
Can someone break it down for me? I understand there is recursion in it, but thats the problem I can’t understand how the recursion in this example works.
It’s actually pretty elegant.
First, we define a function
sievethat takes a list of elements:In the body of
sieve, we take the head of the list (because we’re passing the infinite list[2..], and 2 is defined to be prime) and append it (lazily!) to the result of applyingsieveto the rest of the list:So let’s look at the code that does the work on the rest of the list:
We’re applying
sieveto the filtered list. Let’s break down what the filter part does:filtertakes a function and a list on which we apply that function, and retains elements that meet the criteria given by the function. In this case,filtertakes an anonymous function:This anonymous function takes one argument,
x. It checks the modulus ofxagainstp(the head of the list, every timesieveis called):If the modulus is not equal to 0:
Then the element
xis kept in the list. If it is equal to 0, it’s filtered out. This makes sense: ifxis divisible byp, thanxis divisible by more than just 1 and itself, and thus it is not prime.