Reputation: 15
I have the following haskell code:
a (b : bs) = b : [c | c <- (a bs), c `rem` b /= 0]
Can someone explain what this code does? Running a as
a [3,5..42]
returns
Prelude> a [3,5..42]
[3,5,7,11,13,17,19,23,29,31,37,41*** Exception: <interactive>:71:1-46: Non-exhaustive patterns in function a
From what i can see, the function works like the Sieve of Eratosthenes. The function considers b as a prime number and filters out the multiples of b. But i'm not really sure how. On top of that, the function throws this exception.
Upvotes: 0
Views: 80
Reputation: 71
What you have here is a recursive function: You are calling a bs
in your definition. Eventually bs will be the empty list, and at that point you get an exception. You can, for example, add the following line to your code:
a [] = []
Then the output will become:
[3,5,7,11,13,17,19,23,29,31,37,41]
As for what this function does, it returns every element in the list which is not a multiple of any previous element in the list. If you give it a list [2..x]
where x
is any integer, this is the same thing as a list of all prime numbers from 2
to x
.
Another way of getting a list of primes is the one you've found: You start from 3 and make the Haskell list comprehension skip any multiples of 2.
Upvotes: 6