【问题标题】:How to make this sieve function lazy?如何使这个筛子功能变得懒惰?
【发布时间】:2015-04-18 04:29:22
【问题描述】:

代码如下:

;; Helper function for marking mutiples of a number as 0
(defn mark 
  ([xs k m] (mark xs k m []))
  ([xs k m mark-vec] 
   (loop [[x & rest-xs] xs
          k k
          mark-vec mark-vec
          ]
     (cond 
       (and (nil? x) (nil? rest-xs)) mark-vec
       (= k m) (recur rest-xs 1       (conj mark-vec 0))
       :else   (recur rest-xs (inc k) (conj mark-vec x))
       ))))

;; Sieve of Eratosthenes
(defn sieve
  ([xs] (sieve xs []))
  ([xs sieve-res]
   (loop [[x & rest-xs] xs
          sieve-res sieve-res]
     (cond 
       (and (nil? x) (nil? rest-xs)) sieve-res
       (= x 0) (recur rest-xs sieve-res)
       :else   (recur (mark rest-xs 1 x) (conj sieve-res x))))))

(take 10 (sieve (range 2 100)))

我想让它接收像(iterate inc 2) 这样的东西并生成一个无限的素数序列。

【问题讨论】:

标签: clojure


【解决方案1】:

最好的方法是构建一个适当的功能增量筛,例如 Melissa E. O'Neill 的The Genuine Sieve of Eratosthenes 中描述的那些。

Christophe Grand 发布了一些非常漂亮的增量筛实现 here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-05-19
  • 2010-11-29
  • 2016-09-26
  • 2013-03-20
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多