Chapter 2, Building Abstractions with Data

Section - 2.2 - Hierarchical Data and the Closure Property

Exercise 2.34


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#lang sicp

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

(define (horner-eval x coefficient-sequence)
  (accumulate
        (lambda (this-coeff higher-terms)
              (+ this-coeff (* x higher-terms))
        )        
        0
        coefficient-sequence
  )
)

Example/Output:

1
2
3
> (horner-eval 2 (list 1 3 0 5 0 1))

79