I have a question about Clojure:
I am trying to learn the language by going through Project Euler and I don't understand what is going on under the hood: The following code is designed to use return a list of all prime numbers up to lim
. I would think that it should be O(n) in heap-space because I make a list of all the numbers up to lim
, and then filter them away one by one while moving the first to a new list. (I know that I am actually making new lists each recur but I didn't think they would take more memory?) Anyway I am running this with
(defn getAllPrimes [lim]
(defn getPrimes [primes numlist]
(if (not-empty numlist) ;base case;
(recur (cons (first numlist) primes) ;put the prime on to the prime list
(filter
(fn [x] (not (div? x (first numlist)))) ;remove the prime and all its multiples from the numlist
(rest numlist)))
primes)); return the primes
(getPrimes () (range 2 lim))) ;call the recursive function with and empty prime list to be filled up and a full numlist to be emptied
And I keep running out of heap space, when I call
(apply + (getAllPrimes 2000000))
, but I don't run out of space on
(apply + (filter even? (range 2000000)))
So I think that I must not understand how lists are garbage collected in calls to recur and am actually using O(n*n) heap or something.