【问题标题】:Understanding how a sequence works了解序列的工作原理
【发布时间】:2021-05-31 22:53:37
【问题描述】:

我有以下accumulate函数:

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

【问题讨论】:

  • 通过适当的缩进,您会立即看到它。 pay attention to types,发生了什么。请参阅list? 以及该答案中围绕它的讨论。
  • @tf3 啊,是的,你已经把手指放在上面了。它应该是在我们进行时应该是不言而喻的。如果不是,则意味着读者需要返回并重新阅读,直到它是!在这方面,观看视频也应该有所帮助。

标签: scheme lisp fold sicp accumulate


【解决方案1】:

您的问题是xy 没有告诉您它是什么。但是,如果您查看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

【讨论】:

    【解决方案2】:

    如果您将(lambda (x y) (+ x 1)) 用作op,那么您的length(或者更准确地说,accumulate)函数将不使用递归调用@的结果987654325@ 功能。它基本上只会做一次计算,(+ 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) 时触底,因此当每个嵌套递归调用累加将子列表的长度返回给它们的调用函数时,您最终会得到列表的长度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 2012-12-11
      • 2011-02-18
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多