(defn unfold [step seed]
(if-let [[val new-seed] (step seed)]
(cons val (lazy-seq (unfold step new-seed)))
nil))
使用示例:
(defn fib-step [[x y]] [x [y (+ x y)]])
(take 10 (unfold fib-step [0 1])) ;=> (0 1 1 2 3 5 8 13 21 34)
(defn decreasing [x] (if (neg? x) nil [x (dec x)]))
(unfold decreasing 5) ;=> (5 4 3 2 1 0)
这种功能或类似功能在Clojure标准库(或常用库)中是否存在?如果没有,原因是什么?我找到的最接近的是这篇博客文章:http://www.matlux.net/blog/2014/05/04/anamorphic-adventure-in-clojure。