Search code examples
schemelispfoldsicpaccumulate

Understanding how a sequence works


I have the following accumulate function:

; accumulate
(define (accumulate op initial sequence)
  (if (null? sequence)
      initial
      (op (car sequence) (accumulate op initial (cdr sequence)))))

I'm trying to write a length function to get the length of a sequence using the accumulate function.

For the function to plug into accumulate, why is it (+ y 1) instead of (+ x 1) ? That's the part I can't figure out:

(define (length sequence)
  (accumulate (lambda (x y) (+ x 1)) ; wrong
              0
              sequence))

(define (length sequence)
  (accumulate (lambda (x y) (+ y 1)) ; correct
              0
              sequence))

Solution

  • Your problem is that x and y doesn't tell you anything what it is. However if you look at accumulate you can see how op is called:

    (op (car sequence)                          ; first argument is the element
        (accumulate op initial (cdr sequence))) ; second argument is the accumulated value
    

    While it doesn't really look that way Imagine that the second argument is calling accumulate on the empty sequence. Then you get this:

    (op (car sequence)
        initial)
    

    So lets make length:

    (define (length sequence)
      (accumulate (lambda (element initial) 
                    ;; initial is often also called acc / accumulator
                    (+ 1 initial)) 
                  0
                  sequence))
    

    So the answer is that the first argument is the individual element while the second is either the initial value (0) or the previous calculated value which is 0 with as many 1 added as the tail of the sequence had. Thus a number. WHy you don't use the first argument is that you can't really use "a" or whatever the list contains to count elements since you need to just count them not use them as values. If you use the first argument and it happens to be strings what is (+ "a" 0) supposed to help in finding out that the list has length 1?