gpt4 book ai didi

recursion - clojure 惰性序列和 letfn

转载 作者:行者123 更新时间:2023-12-02 04:41:01 25 4
gpt4 key购买 nike

我正在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com