思路:
- 定义一个求导算法, 令其在抽象对象上执行求导操作。
可以由以下规约规则完成:
dc/dx=0
dx/dx=1
d(u+v)/dx=du/dx+dv/dx
d(uv)/dx=u(dv/dx)+v(du/dx) - 对抽象对象进行具体表示。
实现:
首先,让我们假定现在已经有了一些过程,可以实现对象的判断、构造以及选择。
(variable? x) ;是否为变量?
(same-variable? v1 v2) ;v1、v2是同一变量?
(=number? exp num) ;exp是否为数值且等于num?
(sum? x) ;x为加式?
(product? x) ;x为乘式?
(make-sum a1 a2) ;构造a1+a2
(make-product m1 m2) ;构造a1*a2
(addend s) ;被加数
(augend s) ;加数
(multiplier s) ;被乘数
(multiplicand s) ;乘数
求导函数:
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
(else
(error "unknown expression type -- DERIV" exp))))
判别函数,用来判断所求导的对象以及表达式类型。
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (sum? x)
(and (pair? x) (eq? (car x) '+)))
(define (product? x)
(and (pair? x) (eq? (car x) '*)))
构造函数,构造和式和乘式:
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
;这里的加/乘式构造函数已经将式子进行了一定程度的化简
对加/乘数以及被加/乘数的选择函数。
(define (addend s) (cadr s))
(define (augend s) (caddr s))
(define (multiplier s) (cadr s))
(define (multiplicand s) (caddr s))