2.57
练习 2.57 请扩充求导程序,使之能处理任意项(两项或者更多项)的和与乘积。这样,上面最后一个例子就可以表示为:
(deriv '(* x y (+ x 3)) 'x)
设法通过只修改和与乘积的表示,而完全不修改过程 deriv 的方式完成这一扩充。例如,让一个和式的addend是它的第一项,而其augend是和式中的其余项。
先复用一下前面的代码:
(define (=number? v n)
(if (number? v)
(= v n)
#f
)
)
(define (error msg v)
msg
)
(define variable? symbol?)
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2))
)
(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
((=number? m1 0) 0)
((=number? m2 0) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
(else (list '* m1 m2))
)
)
(define (sum? x) (and (pair? x) (eq? (car x) '+)))
(define addend cadr)
(define augend caddr)
(define (product? x) (and (pair? x) (eq? (car x) '*)))
(define multiplier cadr)
(define multiplicand caddr)
(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-product
(multiplier exp)
(deriv (multiplicand exp) var)
)
(make-product
(deriv (multiplier exp) var)
(multiplicand exp)
)
)
((and (pair? exp) (= 1 (len exp)))
(deriv (car exp) var)
)
(else
(error exp)
)
)
)
; 期待返回 1
(deriv '(+ x 3) 'x)
; 期待得到 3x^2 的结果
(deriv '(** x 3) 'x)
定义 exponentiation?:
(define (exponentiation? exp)
(and (pair? exp) (eq? (car exp) '**))
)
; 期待返回 true
(exponentiation? '(** x 3))
定义 base:
(define base cadr)
; 期待返回 x
(base '(** x 3))
定义 exponent:
(define exponent caddr)
; 期待返回 3
(exponent '(** x 3))
定义 make-exponentiation:
(define (make-exponentiation m1 m2) (list '** m1 m2))
; 期待返回 (** x 3)
(make-exponentiation 'x 3)
增加一个子句后的 deriv:
(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)
)
)
)
((exponentiation? exp)
(cond
((= (exponent exp) 0) 0)
((= (exponent exp) 1) 1)
(else
(make-product
(exponent exp)
(make-exponentiation
(base exp)
(- (exponent exp) 1)
)
)
)
)
)
((and (pair? exp) (= 1 (length exp)))
(deriv (car exp) var)
)
(else
(error "unknown expression type -- DERIV" exp)
)
)
)
(deriv '(** x 0) 'x)
(define addend cadr)
(define (augend exp)
(if (= 1 (length (cddr exp)))
(caddr exp)
(cons '+ (cddr exp))
)
)
(define multiplier cadr)
(define (multiplicand exp)
(if (= 1 (length (cddr exp)))
(caddr exp)
(cons '* (cddr exp))
)
)
; 期待得到 2xy + 3y 的结果
(deriv '(* x y (+ x 3)) 'x)