functional-programming - 过程作为参数 - 方案

标签 functional-programming scheme lisp

我正在使用以下一组方案定义。我的问题专门针对“尾部”功能。这组额外的括号有什么作用,使函数期望将过程作为参数而不是列表,而使用一组括号会出现这种情况?

(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))

我们先看看carcdr会返回什么

(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

的 thunk

关于functional-programming - 过程作为参数 - 方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40253708/

相关文章:

javascript - 使用 Ramda 对键和值对应用不同的函数

f# - 如何确保违法行为无法执行?

algorithm - 以下快速排序的 Haskell 实现是否高效?

function - 重复应用Scheme中的函数?

scheme - 有没有办法从 Racket 中返回 `(values 1 2 3)` 的函数访问第 n 个返回值?

scheme - 为什么可以重新定义 `lambda`?

functional-programming - Lisp - 逻辑运算符

lisp - 写入文件 Common Lisp

emacs - 史莱姆有什么好处?

lisp - 更通用的 lisp 代码来生成对的组合