Kob*_*son 4 clojure lazy-evaluation
我很难理解懒惰.
有人可以帮助我理解为什么我的下面的功能不是懒惰的
(defn my-red
([f coll] (my-red f (first coll) (rest coll) ))
([f init coll]
(let [mr (fn [g i c d]
(if (empty? c) d
(recur g (g i (first c)) (rest c) (conj d (g i (first c)) ))))]
(lazy-seq (mr f init coll [])))))
Run Code Online (Sandbox Code Playgroud)
而在clojure.org/lazy上给出的这个例子是
(defn filter
"Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects."
[pred coll]
(let [step (fn [p c]
(when-let [s (seq c)]
(if (p (first s))
(cons (first s) (filter p (rest s)))
(recur p (rest s)))))]
(lazy-seq (step pred coll))))
Run Code Online (Sandbox Code Playgroud)
在懒惰filter来自呼叫filter在if递归循环的分支.这就是代码击中另一个代码lazy-seq并停止评估seq直到请求另一个元素的地方.
你的实现只能my-red调用lazy-seq一次,这意味着你的seq根本没有被评估或者被完全评估.