理系学生日記

おまえはいつまで学生気分なのか

問題2-34(2.2.3 Sequences as Conventional Interfaces)

a_nx^n+a_{n-1}x^{n-1}+\cdots +a_1x+a_0という形の多項式を(\cdots(a_nx+a_{n-1})x+\cdots+a_1)x+a_0という形に直して計算する方法をHornerの方法とか言います。
こうやると計算回数が若干程度おさえられる。スバらしい!!
これをschemeで書くのが課題です。


accumulate使えば良いみたい。

(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)
		(+ (* x higher-terms)
		   this-coeff))
	      0
	      coefficient-sequence))

x=2のときの1+3x+5x^3+x^5の値を計算します。

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

合ってる!!