请解释“thunks”的编码。

问题描述 投票:0回答:1

我从书中试过以下代码。

;pg 51 "The Scheme Programming Language" by R. Kent Dybvig"
(define lazy
    (lambda (t) ;so lazy accepts argument t
        (let ([val #f] [flag #f]) ;isn't val <- #f (& flag <- #f) ea. time, and if so, how is other val returned?
            (lambda () ;operates on no arguments
                (if (not flag)
                    (begin (set! val (t)) ; if flag == #f (as it initially is) then val <- t, the argument to lazy
                        (set! flag #t)))
                val)))) ; returns val regardless, and executes it?

(define p
    (lazy (lambda () ;so this lambda w/o arguments gets passed to t above
            (display "sig1 ") ;these 2 lines are printed only first time, but why?
            (display "sig2 ")
            "sig 3" ))) ;this seems to get printed every time as if it were the only argument in p to pass to t

; invoke with (p)
; "When passed a thunk t (a zero-argument procedure), lazy returns a new thunk that, when invoked, returns the value of invoking t."
; That is way too convoluted to easily understand!
; What is the new thunk - a copy of the one sent to it, in this case (p)?
; Is this sort of a call-back function?

书上说的,但我看不懂。请参阅下面的评论和问题。我可能在我的评论中假设了不正确的东西。此外,我来自 C 语言背景,并试图了解这种新的编程方式。我是这里的初学者。谢谢!*

scheme lazy-evaluation thunk
1个回答
0
投票

这个 thunk 背后的想法是,除非你需要它,否则它不会被调用,它存储调用包装的 lambda 的值,以便 lambda 只被调用一次。您可以将 thunk 传递给函数,而不必担心不必要地调用它会浪费资源。

是的,lazy是一个回调函数,它接受一个函数t作为参数,返回一个调用t的函数。

显示调用的目的是为了证明被 lazy 包装的 lambda 只被调用一次。标志用于跟踪传入的 lambda 是否已被调用。

函数 lazy 返回它创建的 lambda,关闭局部变量 val 和 flag。 t 是传递给 lazy 的参数,lazy 返回的 lambda 不是任何东西的副本,它可以被调用多次但确保传入的 lambda t 只被调用一次。 p 将保存通过调用 lambda 中的延迟传递返回的函数,将调用包装到显示并返回“sig 3”,该函数作为延迟定义中的 t 传入。

© www.soinside.com 2019 - 2024. All rights reserved.