gpt4 book ai didi

macros - 一个关于scheme语言内存lazy eval宏的问题

转载 作者:行者123 更新时间:2023-12-04 12:28:25 24 4
gpt4 key购买 nike

目前,我一直在看这本书the scheme programming language 由肯特·戴布维格 (Kent Dybvig) 撰写。
5.7 部分,它使用scheme宏系统在scheme中实现了内存的lazy eval。
源代码为

(define-syntax delay
(syntax-rules ()
[(_ expr) (make-promise (lambda () expr))]))

(define make-promise
(lambda (p)
(let ([val #f] [set? #f])
(lambda ()
(unless set?
(let ([x (p)])
(unless set?
(set! val x)
(set! set? #t))))
val))))

(define force
(lambda (promise)
(promise)))
但我不明白为什么变量 set?程序中需要测试两次 make-promise .
这是书中的原因

The second test of the variable set? in make-promise is necessary in the event that, as a result ofapplying p, the promise is recursively forced. Since a promise must always return the same value, the result ofthe first application of p to complete is returned.


我无法理解
谁能给我解释一下?谢谢!

最佳答案

关键是force可能会重新进入自己。也许一个例子可以帮助你理解这一点:

(define x 5)

(letrec ([f (delay
(if (zero? x)
0
(begin
(set! x (- x 1))
(+ (force f) 1))))])
(force f))
结果将是 0 ,因为内部 force调用返回 0。
如果没有第二次测试,结果将是 5 .在这种情况下,每 (force f)返回不同的值。

关于macros - 一个关于scheme语言内存lazy eval宏的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68641043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com