我正在使用以下一组方案定义。我的问题专门针对“尾部”功能。这组额外的括号有什么作用,使函数期望将过程作为参数而不是列表,而使用一组括号会出现这种情况?
(define (make-stream n f)
(define (next m)
(cons m (lambda () (next (f m)))))
(next n))
(define head car)
(define (tail stream)
((cdr stream)))
(define (nth stream n)
(if (= n 0) (head stream)
(nth (tail stream) (- n 1))))
(define even (make-stream 0 (lambda (n) (+ n 2))))
抱歉,如果格式不正确或者是一个不恰当的问题,我正在努力学习如何使用这个网站。
最佳答案
My question is specifically about the "tail" function. What does the extra set of parentheses do that makes the function expect a procedure as an argument instead of a list, which would be the case with one set of parentheses?
这是你的程序
(define (make-stream n f)
(define (next m)
(cons m (lambda () (next (f m)))))
(next n))
我们先看看car
和cdr
会返回什么
(car (make-stream 0 f) ; => 0
(cdr (make-stream 0 f) ; => (lambda () (next (f m)))
car
返回的这个无效(零参数)过程称为 Thunk .它通常用于延迟计算的评估。在这种情况下,它用于防止 make-stream
在为 make-stream
提供其两个参数后立即无限递归。
为了得到下一个值,我们所要做的就是应用thunk。这次注意额外的括号
((cdr (make-stream 0 f))) ;=> (next (f m))
这就是为什么你看到...
(define (tail stream) ((cdr stream)))
... 将返回下一个 cons
,而不是 ...
(define (tail stream) (cdr stream))
... 这将返回一个包含下一个 cons
关于functional-programming - 过程作为参数 - 方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40253708/