Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I believe the problem is that with each recur, you're creating a new lazy sequence referring to the last one, so after a few iterations you're holding a seq that holds the head of a seq that holds the head of a seq that holds the head of a seq. ... All the intermediate seqs are filling up your heap.</p> <p>Though writing a prime sieve is a worthwhile exercise, if you want to get to the answer, Clojure does include the sequence of prime numbers in its standard library: clojure.contrib.lazy-seqs/primes. The standard solution to this paricular Euler problem is a one-liner.</p> <p>As a style point, an inner defn is not a good idea. The practical effect is the same as if the defn were at the top level, but if I'm not mistaken, the var gets reassigned every time getAllPrimes is called, and redefining vars at runtime is very strongly discouraged. Since the code is just defining a var, getPrimes is still just as visible as getAllPrimes. In this case, getPrimes could easily be rewritten as a loop/recur with no inner function, anonymous or named. That doesn't help your chain-of-lazy-seqs problem, but it does make the code a little more standard-looking:</p> <pre><code>(defn getAllPrimes [lim] (loop [primes () numlist (range 2 lim)] (if (not-empty numlist) (recur (cons (first numlist) primes) (filter (fn [x] (not (div? x (first numlist)))) (rest numlist))) primes))) </code></pre> <p>I would also avoid the use of camelCase. The Clojure standard name for this function would be get-all-primes.</p> <p>Getting back to the practical problem, though, the least work you could do to get your code working would be to force each seq on each iteration, i.e., wrap your filter call in a doall. I tried this, and while it still runs slowly, it at least does run to completion without running out of heap:</p> <pre><code>(defn get-all-primes [lim] (loop [primes () numlist (range 2 lim)] (if (not-empty numlist) (recur (cons (first numlist) primes) (doall (filter #(not (div? % (first numlist))) (rest numlist)))) primes))) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload