方案,SICP,R5RS,为什么延迟不是一种特殊形式? [英] Scheme, SICP, R5RS, why is delay not a special form?
问题描述
这与SICP的第3.5章有关,其中正在讨论流.这个想法是:
This is concerning chapter 3.5 from SICP, in which streams are being discussed. The idea is that:
(cons-stream 1 (display 'hey))
不应评估cons流的第二部分,因此不应打印嘿".确实发生了,我得到以下输出:
Should not evaluate the second part of the cons-stream, so it should not print "hey". This does happen, I get the following output:
hey(1.#< promise>)
所以我的结论是,延迟不是以特殊形式实现的吗?还是我做错了什么?我使用以下实现:
So my conclusion is that delay is not implemented as a special form? Or am I doing something wrong? I use the following implementation:
(define (cons-stream a b)
(cons a (delay b)))
延迟是默认的R5RS实现.这是实现上的错误吗,还是我没有做或不正确理解它?
With delay being the default R5RS implementation. Is this a fault in the implementation, or am I not doing or understanding it right?
推荐答案
您做创建了一个promise,但是该promise是在您的cons-stream
内部创建的,这意味着为时已晚,并且该表达式已被评估.试试这个:
You do create a promise, but the promise is created inside your cons-stream
, which means that it's too late and the expression was already evaluated. Try this:
(define (foo x)
(display "foo: ") (write x) (newline)
x)
(cons-stream 1 (foo 2))
,您将发现评估还为时过早.出于同样的原因,这是
and you'll see that it's evaluated too early. For the same reason, this:
(define ones (cons-stream 1 ones))
当cons-stream
是一个函数时,
和任何其他无限列表将不起作用.因此,事实是delay
是一种特殊形式,但是您没有使用它的功能,因为您将cons-stream
定义为普通函数.如果要使 it 以相同的特殊方式运行,则必须将cons-stream
定义为宏.例如:
and any other infinite list won't work when your cons-stream
is a function. So the thing is that delay
is a special form, but you're not using its feature since you define cons-stream
as a plain function. You have to define cons-stream
as a macro if you want to make it behave in the same special way too. For example:
(define-syntax cons-stream
(syntax-rules ()
[(cons-stream x y) (cons x (delay y))]))
这篇关于方案,SICP,R5RS,为什么延迟不是一种特殊形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!