Sieve of Eratosthenes infinite list

两盒软妹~` 提交于 2019-12-12 11:37:52

问题


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:

  1. You want to define a sieve list that should be the list of primes, but in the where you shadow the name sieve with a function. Inside this definition you use sieve 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.

  2. In mod x p it should be mod x h since h is the prime you are considering there.

  3. You are defining sieve (h:t) = h:removep ... :_ But here you are creating a list where the first element is h, a number, the second element is removep ..., which is a list, and then the remaining elements are taken by sieve (which is incorrect as already said.

  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!