scheme中的序列操作
本节对序列操作进行总的抽象介绍。
从两个程序入手:
(define (sum-odd-square tree)
(cond ((null? tree) 0)
((not (pair? tree))
(if (odd? tree) (square tree) 0))
(else (+ (sum-odd-square (car tree))
(sum-odd-square (cdr tree))))))
(define (even-fibs n)
(define (next k)
(if (> k n)
nil)
(let ((f (fib k)))
(if (even? f)
(cons f (next (+ k 1)))
(next (+ k 1)))))
(next 0))
第一个程序,枚举一棵树的树叶,过滤其中的奇数,对选出的每一个数进行平方,从0开始累加
第二个程序,枚举从0到n的整数,计算其中的斐波那契数列,过滤其中的偶数,用cons累积结果
容易总结出,这两个程序的基本流程都是枚举-过滤-计算-累积,如果我们能将该流程进行抽象,抽象成过滤器-映射-累积器的形式,能使得这个流程更加清晰。
点击查看代码
;遍历
(define (enumerate-tree tree)
(cond ((null? tree) nil)
((not(pair? tree)) (list tree))
(else (append (enumerate-tree (car tree))
;过滤
(define (filter predicate sequence)
(cond ((null? sequence) nil)
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
;累积
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
点击查看代码
(define (map p sequence)
(accumulate (lambda (x y) (cons (p x) y)) nil sequence))
(define (append seq1 seq2)
(accumulate cons seq1 seq2))
(define (length sequence)
(accumulate (lambda (x y)(+ 1 y) 0 sequence)))
练习2.34 对于x的某个给定值,求出一个多项式在x的值,也可以形式化为一种累积。假定需要求下面多项式的值:
anxn+an-1xn-1……+a1x+a0
这里可以采用著名的Horner规则,构造下面的计算:
(……(anx+an-1)x+……+a1)x+a0
请填充下面的模板,做出一个利用Horner规则求多项式值的过程。
点击查看代码
;完整的就是这样了,根据Horner的规则,做(高项*x+低项)*x……的翻译即可
(define (horner-eval x coefficient-sequence)
(accumulate(lambda (this-coeff higher-terms) (+ this-coeff (* x higher-terms)))
0
coefficient-sequence)
)

浙公网安备 33010602011771号