SICP 2.34多项式加法

对于一个多项式:
这里写图片描述
求值,我们可以化简找出其规律,利用Horner 规则化简:
这里写图片描述
可以明显看出多项式的递归规律:从an开始,(+ (* an x) a(n-1)),下一个也是如此,直到a0。
之前建立的accumulate过程,也有相似的递归性,应该是一类过程,accumulate的原始定义:

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

op 是对数据的操作,从简单的加减乘除到复杂的自定义运算。
initial是初始数据,说明它是个什么的累加,比如数或者表
sequence是待处理的数据

那么结合此多项式的计算规律,对于多项式的计算可以抽象成代码:

(define (hover_eval x sequence)
    (accumulate (lambda (this_coeff higher_terms)
        (+ (* x this_coeff) higher_terms))
        0
        sequence))

手动模拟线性递归过程:

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

(accumulate (lambda (this-coeff higher-terms) <??>)
            0
            (list 1 3 0 5 0 1))

(+ 1 (* 2
        (accumulate (lambda (this-coeff higher-terms) <??>)
                    0
                    (list 3 0 5 0 1))))

(+ 1 (* 2
        (+ 3 (* 2 (accumulate (lambda (this-coeff higher-terms) <??>) 0 (list 0 5 0 1))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (accumulate (lambda (this-coeff higher-terms) <??>) 0 (list 5 0 1))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (accumulate (lambda (this-coeff higher-terms) <??>) 0 (list 0 1))))))))))
(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (+ 0 (* 2 (accumulate (lambda (this-coeff higher-terms) <??>) 0 (list 1))))))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (+ 0 (* 2 (+ 1 (* 2 (accumulate (lambda (this-coeff higher-terms) <??>) 0 '())))))))))))))
(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (+ 0 (* 2 (+ 1 (* 2 0))))))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (+ 0 (* 2 (+ 1 0)))))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (+ 0 (* 2 1))))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 (+ 0 2)))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 (* 2 2))))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 (+ 5 4)))))))

(+ 1 (* 2
        (+ 3 (* 2
                (+ 0 (* 2 9))))))

(+ 1 (* 2
        (+ 3 (* 2 18))))

(+ 1 (* 2 (+ 3 36)))

(+ 1 (* 2 39))

(+ 1 78)

79
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值