如何解决了解序列的工作原理
; accumulate
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence) (accumulate op initial (cdr sequence)))))
我正在尝试编写一个 length
函数来使用 accumulate
函数获取序列的长度。
对于插入 accumulate
的函数,为什么是 (+ y 1)
而不是 (+ x 1)
?这是我无法弄清楚的部分:
(define (length sequence)
(accumulate (lambda (x y) (+ x 1)) ; wrong
0
sequence))
(define (length sequence)
(accumulate (lambda (x y) (+ y 1)) ; correct
0
sequence))
解决方法
您的问题是 x
和 y
没有告诉您它是什么。但是,如果您查看 accumulate
,您会看到如何调用 op
:
(op (car sequence) ; first argument is the element
(accumulate op initial (cdr sequence))) ; second argument is the accumulated value
虽然看起来不是那样,但想象一下,第二个参数在空序列上调用 accumulate
。然后你会得到这个:
(op (car sequence)
initial)
所以让length
:
(define (length sequence)
(accumulate (lambda (element initial)
;; initial is often also called acc / accumulator
(+ 1 initial))
0
sequence))
所以答案是第一个参数是单个元素,而第二个参数是初始值 (0
) 或先前计算的值 0
和 1
添加为序列的尾部。于是一个数。为什么不使用第一个参数是因为您不能真正使用 "a"
或列表中包含的任何内容来计算元素,因为您只需要计算它们而不是将它们用作值。如果您使用第一个参数并且它恰好是字符串,那么 (+ "a" 0)
应该有助于找出列表的长度为 1
吗?
如果您将 (lambda (x y) (+ x 1))
用作 op
,那么您的 length
(或准确地说是 accumulate
)函数将不使用递归调用 accumulate
函数的结果。它本质上只会做一个计算, (+ x 1)
,其中 x
是 (car sequence)
,sequence
的第一个元素——这个计算可能甚至可能不有道理,取决于 x
是否是数字,即使是,答案也是错误的。
另一方面,如果 op
是 (lambda (x y) (+ y 1))
,那么您的函数将替换
(op (car sequence) (accumulate op initial (cdr sequence)))
与
(+ (accumulate op initial (cdr sequence)) 1)
递归以计算 (+ 0 1)
为底,因此您最终得到列表的长度,当每个嵌套的递归调用累加将子列表的长度返回给它们的调用函数时。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。