clojure 中的lazy-seq 有什么意义?
我正在查看一些示例斐波那契序列 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
[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 beforefibs
is bound to a value, which will cause an exception. By wrapping it inlazy-seq
, the call will be deferred until the value is needed, andfibs
will have a value at that point.据我了解(我承认对 Clojure 来说还是个相对较新的人!),如果您尝试以下操作:
那么它将不起作用,因为 fibs 尚未绑定,因此后面对它的两次引用都会失败。
然而,您提供的惰性版本将起作用,因为对 fibs 的引用仅在稍后使用序列时才实际解析 - 此时 fibs 已成功定义为惰性序列。
As I understand it (and I admit to still being a relative newcomer to Clojure!), if you try the following:
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.