这是我的clojure素数序列,用惰性序列lazy-seq实现
(def primes
(letfn [(primes-parts [part]
(lazy-seq
(when-let [[p & xs] (seq part)]
(let [cannot-div? #(not= 0 (mod % p))]
(cons p (primes-parts (filter cannot-div? xs)))))))]
(primes-parts (iterate inc 2))))
或是这样写,可读性高一点
(defn is-prime? [n]
(let [nums (range 2 (inc (int (Math/sqrt n))))]
(not
(some #(zero?
(mod n %)) nums))))
;; 递归
(defn primes-part [nums]
(lazy-seq
(let [[f & rst] nums]
(cons f (primes-part (filter is-prime? rst))))))
(def primes-2 (primes-part (iterate inc 2)))
当我正在repl中调试,发现有哪里不对
(count (take 100000 primes)) ;;1789
(count (take 100000 (repeat 1))) ;; 100000
这个我有点慌,求助