2.57

练习 2.57 请扩充求导程序，使之能处理任意项（两项或者更多项）的和与乘积。这样，上面最后一个例子就可以表示为：

(deriv '(* x y (+ x 3)) 'x)


(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 (product? x) (and (pair? x) (eq? (car x) '*)))

(define (deriv exp var)
(cond
((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0)
)
((sum? exp)
(make-sum
(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)


(define (exponentiation? exp)
(and (pair? exp) (eq? (car exp) '**))
)

; 期待返回 true
(exponentiation? '(** x 3))


(define base cadr)

; 期待返回 x
(base '(** x 3))


(define exponent caddr)

; 期待返回 3
(exponent '(** x 3))


(define (make-exponentiation m1 m2) (list '** m1 m2))

; 期待返回 (** x 3)
(make-exponentiation 'x 3)



(define (deriv exp var)
(cond
((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0)
)
((sum? exp)
(make-sum
(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)))
(cons '+ (cddr exp))
)
)
(define (multiplicand exp)
(if (= 1 (length (cddr exp)))