我有一个关于Clojure的问题: 我想通过Project Euler去学习语言,我不明白底下发生了什么:下面的代码是为了使用返回所有素数列表,最高可达lim
。我认为它应该是堆空间中的O(n),因为我列出了所有数字列表,最多为lim
,然后逐个将它们过滤掉,同时将第一个移动到新列表中。 (我知道,我其实做新列出了每个易复发,但我没想到他们会采取更多的内存?)反正我与关于Clojure堆和垃圾的初级问题
(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
运行这和我保持运行的堆空间不足,当我打电话
(apply + (getAllPrimes 2000000))
,但我不上
(apply + (filter even? (range 2000000)))
用完的空间,所以我认为我不能明白名单是如何收集垃圾的通话复发和我实际使用O(N * n)堆什么的。
这是以前在这里找到答案:简单的答案是,过滤器创建一个懒惰的序列,你正在调用过滤器过滤...并最终堆栈溢出。解决这个问题的方法之一就是通过“doall”来实现序列的每一步。 –
2010-08-11 04:12:03