【问题标题】:clojure lazy sequences and letfnclojure 惰性序列和 letfn
【发布时间】:2013-12-30 10:22:41
【问题描述】:

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

我错过了什么?

【问题讨论】:

    标签: recursion clojure


    【解决方案1】:

    在 letfn 定义中少一个括号,多一个括号来调用 natz 函数

    (defn natz[]
      (letfn [(aux [n] (cons n (lazy-seq (aux (inc n)))))]
        (aux 0)))
    

    示例用法:

    (take 4 (natz))
    => (0 1 2 3)
    

    【讨论】:

      猜你喜欢
      • 2021-05-25
      • 1970-01-01
      • 2011-06-26
      • 2010-12-08
      • 2014-06-17
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多