SICP solution exercise 2.34

Solution for exercise 2.34 of 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))
;-------------------- tests --------------------

;1 + 3x + 5x^3 + x^5 at x = 2
(horner-eval 2 (list 1 3 0 5 0 1))

;1 + 3x + 2x^2 + 5x^3 + +3x^4 + x^5 at x = 2
(horner-eval 2 (list 1 3 2 5 3 1))

;2 - 4x + 5x^2 + 7x^3 at x = 2
(horner-eval 2 (list 2 -4 5 7))

This entry was posted in SICP and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>