我在哪里失去懒惰?

时间:2015-01-30 12:48:53

标签: clojure

我正在尝试编写一个懒惰的迭代主筛。

筛子的每次迭代都由

表示
[[primes] (candidates) {priority-map-of-multiples-of-primes}]

我有一个函数,筛选下一个候选者更新,快乐地进行筛选迭代,检查下一个候选者,并适当地更新所有三个组件。

像这样使用:

(take 3 (iterate sieve-next-candidate-update [[2] (range 3 13 2) (priority-map 2 2)]))

我得到了我期望的结果:

([[2] (3 5 7 9 11) {2 2}]
 [[2 3] (5 7 9 11) {3 3, 2 4}]
 [[2 3 5] (7 9 11) {5 5, 2 6, 3 6}])

但是,当我通过reduce运行它来删除没有找到新素数的迭代时,它会尝试处理整个序列,但是我定义了初始候选列表(如果我使用迭代,那么表观无限循环)。

(take 3 
   (reduce (fn [old-primes-sieves new-sieve]
             (prn (str "reduce fn called with new sieve" new-sieve))
             (if (= (last (first (last old-primes-sieves))) ; I'm aware I don't want last in the final version
                    (last (first new-sieve)))
               old-primes-sieves
               (conj old-primes-sieves new-sieve)))
           []
           (iterate sieve-next-candidate-update [[2] (range 3 13 2) (priority-map 2 2)])))

输出

"reduce fn called with new sieve[[2] (3 5 7 9 11) {2 2}]"
"reduce fn called with new sieve[[2 3] (5 7 9 11) {3 3, 2 4}]"
"reduce fn called with new sieve[[2 3 5] (7 9 11) {5 5, 2 6, 3 6}]"
"reduce fn called with new sieve[[2 3 5 7] (9 11) {7 7, 2 8, 3 9, 5 10}]"
"reduce fn called with new sieve[[2 3 5 7] (11) {3 9, 2 10, 5 10, 7 14}]"
"reduce fn called with new sieve[[2 3 5 7 11] nil {11 11, 2 12, 3 12, 7 14, 5 15}]"

然后在这种有限的情况下抛出NullPointerException。

我在哪里失去懒惰?

1 个答案:

答案 0 :(得分:3)

reduce不是懒惰的 - 它会尝试迭代整个无限序列(iterate sieve-next-candidate-update [[2] (range 3 13 2) (priority-map 2 2)])。您可以改为使用reductions

顺便说一下,clojure.contrib here可以找到有效无限素数序列的好例子。