clojure 中的lazy-seq 有什么意义?

发布于 2024-09-03 19:12:59 字数 439 浏览 9 评论 0原文

我正在查看一些示例斐波那契序列 clojure 代码:

 (def fibs (lazy-cat [1 2] (map + fibs (rest fibs))))

我大致了解发生了什么,但不明白 lazy-cat 的要点。 我知道 lazy-cat 是一个宏,它会翻译成这样:

(def fibs (concat (lazy-seq [1 2]) (lazy-seq (map + fibs (rest fibs))))) 

lazy-seq 到底要完成什么?即使没有lazy-seq,它仍然会被延迟评估?这是否严格用于缓存目的?

编辑:感谢您的回答。我感到困惑的是,它与 REPL 中的普通 concat 一起工作,因为我之前在范围内绑定了 fibs。

I am looking through some example Fibonacci sequence clojure code:

 (def fibs (lazy-cat [1 2] (map + fibs (rest fibs))))

I generally understand what is going on, but don't get the point of lazy-cat.
I know that lazy-cat is a macro that is translating to something like this:

(def fibs (concat (lazy-seq [1 2]) (lazy-seq (map + fibs (rest fibs))))) 

What exactly is lazy-seq accomplishing? It would still be evaluated lazily even without lazy-seq? Is this strictly for caching purposes?

EDIT: Thanks for the answers. My confusion was that it worked with a plain concat from the REPL because I had a previous binding to fibs in scope.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

飘落散花 2024-09-10 19:12:59

[1 2] 上的 lazy-seq 不是必需的,但也没什么坏处。

(map + fibs (rest fibs)) 上的 lazy-seq 是必不可少的;如果没有它,函数调用将在 fibs 绑定到值之前进行评估,这将导致异常。通过将其包装在lazy-seq中,调用将被推迟,直到需要该值为止,并且fibs此时将有一个值。

The lazy-seq on [1 2] is not needed, but doesn't really hurt.

The lazy-seq on (map + fibs (rest fibs)) is essential; without it, the function call will be evaluated before fibs is bound to a value, which will cause an exception. By wrapping it in lazy-seq, the call will be deferred until the value is needed, and fibs will have a value at that point.

凝望流年 2024-09-10 19:12:59

据我了解(我承认对 Clojure 来说还是个相对较新的人!),如果您尝试以下操作:

(def fibs (concat [1 2] (map + fibs (rest fibs))))

那么它将不起作用,因为 fibs 尚未绑定,因此后面对它的两次引用都会失败。

然而,您提供的惰性版本将起作用,因为对 fibs 的引用仅在稍后使用序列时才实际解析 - 此时 fibs 已成功定义为惰性序列。

As I understand it (and I admit to still being a relative newcomer to Clojure!), if you try the following:

(def fibs (concat [1 2] (map + fibs (rest fibs))))

Then it won't work because fibs isn't yet bound and therefore the two later references to it fail.

The lazy version you give will however work, because the references to fibs are only actually resolved at a later time when the sequence is consumed - and by which point fibs has already been successfully defined as the lazy sequence.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文