问题
Hello i have to implement a function for sieve of Eratosthenes.
I already have a function
removep p l
that removes elements of l
that match the predicate p
and a function
nats
that returns an infinite list of naturals numbers, and i am supposed to use both in my solution.
Now, i do understand how the sieve itself works but it seems i am having problems implementing this.
I am doing something like this:
sieve = (drop 1 nats)
where
sieve (h:t) = h : (removep (\x -> (mod x p) == 0) t) : sieve
but this doesn't seem to work. Any help? Also note that this is an assignment so if possible do not give away the exact solution. Id rather get an idea of what i am doing wrong and how i need to change it. Thanks in advance.
回答1:
The basic idea is that you get the list of nats
as a starting point for sieve. Then you recursively apply your removep
function with your predicate to all but the first elements.
You are close, but i think your problem lies in the notation (see Bakuriu's answer) I won't give you the answer but i will give you a hint:
sieve = s (drop 1 nats)
where
-- Recursive definition of s here
-- s (h:t) = ???
I hope i didn't give away too much to make it trivial. Good luck.
PS: As Bakuriu mentioned, this is really not a true sieve. For more info on the matter, take a look here
回答2:
There are a few errors in your code:
You want to define a
sieve
list that should be the list of primes, but in thewhere
you shadow the namesieve
with a function. Inside this definition you usesieve
as a list, but here it actually references the function and thus you get a typeerror.You want to apply a function to
drop 1 nats
to obtain the list of primes.In
mod x p
it should bemod x h
sinceh
is the prime you are considering there.You are defining
sieve (h:t) = h:removep ... :_
But here you are creating a list where the first element ish
, a number, the second element isremovep ...
, which is a list, and then the remaining elements are taken bysieve
(which is incorrect as already said.Nitpicking: technically this is not the sieve of eratosthenes because in the algorithm of the sieve you never actually use
mod
to check for divisibility.
来源:https://stackoverflow.com/questions/34770836/sieve-of-eratosthenes-infinite-list