Recursive function causing a stack overflow

Posted by dbyrne on Stack Overflow See other posts from Stack Overflow or by dbyrne
Published on 2010-06-01T01:05:47Z Indexed on 2010/06/01 1:13 UTC
Read the original article Hit count: 256

Filed under:
|
|
|

I am trying to write a simple sieve function to calculate prime numbers in clojure. I've seen this question about writing an efficient sieve function, but I am not to that point yet. Right now I am just trying to write a very simple (and slow) sieve. Here is what I have come up with:

(defn sieve [potentials primes]
  (if-let [p (first potentials)]
    (recur (filter #(not= (mod % p) 0) potentials) (conj primes p))
    primes))

For small ranges it works fine, but causes a stack overflow for large ranges:

user=> (sieve (range 2 30) [])
[2 3 5 7 11 13 17 19 23 29]
user=> (sieve (range 2 15000) [])
java.lang.StackOverflowError (NO_SOURCE_FILE:0)

I thought that by using recur this would be a non-stack-consuming looping construct? What am I missing?

© Stack Overflow or respective owner

Related posts about beginner

Related posts about recursion