# 2.56

## 练习 2.56 请说明如何扩充基本求导规则，以便能够处理更多种类的表达式。例如，通过给程序deriv增加一个新子句，并以适当方式定义过程exponentiation?、base、exponent和make-exponentiation的方式，实现下述求导规则（你可以考虑用符号**表示乘幂）：

$\frac{d(u^n)}{dx}=nu^{n-1}(\frac{du}{dx})$

## 请将如下规则也构造到程序里：任何东西的0次幂都是1，而它们的1次幂都是其自身。

; 期待得到 3x^2 的结果
(deriv '(** 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) (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)
)
)
(else
(error "unknown expression type -- DERIV" 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-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)
)
)
)
)
)
(else
(error "unknown expression type -- DERIV" exp)
)
)
)

(deriv '(** x 0) 'x)

; 期待得到 3x^2 的结果
(deriv '(** x 3) 'x)