简体   繁体   English

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

[英]Whats the point of lazy-seq in clojure?

I am looking through some example Fibonacci sequence clojure code: 我正在看一些斐波那契序列Clojure代码示例:

 (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 . 我通常理解发生了什么,但是不明白lazy-cat I know that lazy-cat is a macro that is translating to something like this: 我知道lazy-cat是一个宏,它会翻译成如下形式:

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

What exactly is lazy-seq accomplishing? lazy-seq到底能完成什么工作? It would still be evaluated lazily even without lazy-seq ? 即使没有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. 我的困惑是,它与REPL的普通concat使用,因为我以前曾将示波器绑定到范围上。

The lazy-seq on [1 2] is not needed, but doesn't really hurt. 不需要[1 2]上的lazy-seq ,但是并没有真正的伤害。

The lazy-seq on (map + fibs (rest fibs)) is essential; (map + fibs (rest fibs))上的lazy-seq是必不可少的; without it, the function call will be evaluated before fibs is bound to a value, which will cause an exception. 没有它,函数调用将在fibs绑定到一个值之前进行评估,这将导致异常。 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. 通过将其包装在lazy-seq ,调用将被推迟到需要该值时为止,而fibs届时将具有一个值。

As I understand it (and I admit to still being a relative newcomer to Clojure!), if you try the following: 据我了解(并且我承认仍然是Clojure的相对新手!),如果您尝试以下操作:

(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. 然后它将无法工作,因为尚未绑定fib,因此以后对其的两次引用都失败了。

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. 但是,您给出的延迟版本将起作用,因为对fibs的引用仅在序列被消耗时才实际解析,并且到那时fib已被成功定义为lazy序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM