首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让这个sieve函数变得懒惰?

如何让这个sieve函数变得懒惰?
EN

Stack Overflow用户
提问于 2015-04-18 01:44:44
回答 1查看 115关注 0票数 0

代码如下:

代码语言:javascript
复制
;; 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)这样的东西,并生成一个无限的素数序列。

EN

回答 1

Stack Overflow用户

发布于 2015-04-18 04:29:23

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29706098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档