内部延迟序列如何工作 [英] How exactly work internally lazy sequence

查看:57
本文介绍了内部延迟序列如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Clojure还是陌生的,目前尚不清楚内部懒惰序列在内部如何工作,或者更具体地讲,返回懒惰序列的函数意味着仅在需要时才计算结果。例如,在下面的示例中:

I'm new on clojure and it's not clear how exactly work lazy-sequence internally or to be more specific a function that return a lazy sequence mean that the result will be computed only when is needed. For example in the following example:

(defn fc-lazy [ fn xs ]
 (lazy-seq
  (if-let [ xss (seq xs) ]
   (cons (fn (first xs)) (fc-lazy fn (rest xs)))
  ())))

当我打电话时:

(fc-lazy #(* % 2) (range 100))

结果为100个数字的集合,这意味着fc-lazy函数将被调用100次,这对我来说还不清楚;在这种情况下,我们拥有所有这100个函数,如果没有,为什么?

result will be a collection of 100 numbers, this mean that the fc-lazy function will be called for 100 times, what is not clear to me; in this case we have on stack all those 100 functions, if NOT, why ?

谢谢。

推荐答案

我认为它是这样工作的。

I imagine it works this way.

lazy-seq


  • 将其表达式形式的参数转换为函数形式,

  • 将其转换为Clojure闭包(调用符合
    IFn 接口的JVM类上的
    方法)

  • 将该函数绑定为-

  • 类中的新 LazySeq 对象,

  • 在其中保留了一个空洞以实现序列。

  • transforms its expression-form argument into a function-form,
  • compiles it into a Clojure closure (an invoke method on a JVM class complying with the IFn interface)
  • binds this function-class to a new LazySeq object,
  • leaving a null hole in it for the realized sequence.

在此阶段,该表达式已被捕获为对象中的功能对象,而不是评估产生序列的表达式看起来(因此是)序列。

At this stage, instead of evaluating the expression that yields the sequence, the expression has been captured as a function-object in an object that looks like (and therefore is) a sequence.

使用某些功能时,例如 first next 或需要实现序列的 seq LazySeq

When some function, such as first or next or seq, that requires the realized sequence, is called on the LazySeq,


  • 它注意到空洞并调用捕获的闭包,

  • 用结果填充空洞,

  • 应用了所需功能的

  • 返回结果的结果。

  • it notes the null hole and invokes the captured closure,
  • filling the hole with the result,
  • to which the required function is applied
  • the result of which is returned.

随后的调用找到填充的孔,并立即返回其所需的外观。

Subsequent calls find the hole filled, and return its required aspect at once.

因此,当您遍历序列时,确实会收到一百个呼叫,但是一次只能一次,而不是一次全部。

So, as you run through the sequence, you do get your hundred calls, but one at a time, not all at once.

对于任何需要的更正,我将不胜感激。

I'd be grateful for any corrections required.

这篇关于内部延迟序列如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆