首页 > 解决方案 > 了解序列的工作原理

问题描述

我有以下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))

标签: schemelispfoldsicpaccumulate

解决方案


你的问题是,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初始01(因而有数。为什么你不使用第一个参数是你不能真正使用"a"或列表包含的任何元素来计算元素,因为你只需要计算它们而不将它们用作值。如果您使用第一个参数并且它恰好是字符串,那么(+ "a" 0)应该帮助找出列表有长度1吗?


推荐阅读