我正在 Clojure 中尝试一些惰性流。 如果我这样做:
(defn ints-from [n]
(cons n (lazy-seq (ints-from (inc n)))))
和
(def nats (ints-from 0))
没关系,我可以做这样的事情:
(take 5 nats)
现在我尝试将 2 个函数封装在 1 个函数中:
(defn natz[]
( letfn [(aux [n]((cons n (lazy-seq (aux (inc n)))))) ] (aux 0) ))
这似乎可以编译,但没有达到我的预期。
(take 4 natz)
给出:
(user=> IllegalArgumentException Don't know how to create ISeq from: user$natz
clojure.lang.RT.seqFrom (RT.java:494)
我错过了什么?
最佳答案
letfn 定义中少一个括号,多一个括号来调用 natz 函数
(defn natz[]
(letfn [(aux [n] (cons n (lazy-seq (aux (inc n)))))]
(aux 0)))
使用示例:
(take 4 (natz))
=> (0 1 2 3)
关于recursion - Clojure 惰性序列和 letfn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20837548/