sicp-ex-1.32



<< Previous exercise (1.31) | sicp-solutions | Next exercise (1.33) >>


a. Accumulate procedure

Recursive process:

  ; right fold 
  (define (accumulate combiner null-value term a next b) 
    (if (> a b) null-value 
        (combiner (term a) (accumulate combiner null-value term (next a) next b)))) 

Sum and product as simple calls to accumulate:

  (define (sum term a next b) (accumulate + 0 term a next b)) 
  
  (define (product term a next b) (accumulate * 1 term a next b)) 

b. Iterative process:

  ; left fold 
  (define (accumulate combiner null-value term a next b) 
    (define (iter a res) 
      (if (> a b) res 
          (iter (next a) (combiner res (term a))))) 
    (iter a null-value))