实践一
语言:scheme
lisp中每个函数形成了一个闭包,函数和函数复合形成了一个新的闭包,然后和其他的函数符合,可以组成更加复杂的闭包。
(define (compose f g)
(lambda (x)
(f (g x))))
将两个函数复合,形成的新函数接受一个参数
(define (compose-n f n)
(if (= n 1)
f
(compose f (compose-n f (- n 1)))))
将f复合n次,得到的函数是:f(f(f(....f(x)))))
(define f1
(lambda (x) (* x x)))
(define f4 (compose-n f1 4))
(f4 2)
这个函数经过复合后,得到的函数为X^(2^4) = X^16
2^16=1024^64=65536
实践二
SICP1.44中的一道习题:将一个函数平滑得到的效果是
Smooth(f(x)) = (f(x) + f(x+dx)+f(x-dx))/3
要求将一个函数做n次平滑
令G(x)=Smooth(f(x))
=Smooth(smooth(fx))
下面这个函数复合并不是很好理解,可以通过Smooth(G(x)), G(x)=Smooth(F(x)) ........Z(x)=Smooth (smooth f)
(define (smooth f)
(lambda (x)
(/ (+ (f x) (f (+ x dx)) (f (- x dx))) 3)))
(define (smooth-n f n)
((compose-n smooth n) f))
因为每次smooth需要计算3次,所有这个函数的计算复杂度为3^n
求解1.....n的和或者1........n的积,并且求解F(1)....F(n)的和或者积或者其他
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
(define (sum-a term a next b)
(accumulate + 0 term a next b))
(define (product-a term a next b)
(accumulate * 1 term a next b))
这样就将两个问题统一起来。
演化
lisp中的函数是闭包的,导致语言的组合能力非常强大,这个和C++中的function有点类似,但是更加好用和灵活。