Read Exercise 2.73 ~ Solution 73a
a
(define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) (else ((get 'deriv (operator exp)) (operands exp) var)))) (define (operator exp) (car exp)) (define (operands exp) (cdr exp))
Instead of checking the type of expression and performing the derivation in the body of deriv, each type of expression has a separate procedure defined. These procedures are installed with appropriate operators in the dispatch table. If the expression isn’t a number or variable the procedure is obtained from the dispatch table, based on the operator and is evaluated passing in the operands. The operator and operands are taken from the expression.
Number and variable expressions don’t use operators or operands so the same generic dispatch mechanism can’t be used.
b
(define (deriv-sum exp var) (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) (define (deriv-product exp var) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) (define (install-deriv) (put 'deriv '+ deriv-sum) (put 'deriv '* deriv-product) 'done)
c
(define (deriv-exponentiation expr var) (let ((base (base expr)) (exponent (exponent expr))) (make-product exponent (make-product (make-exponentiation base (make-sum exponent -1)) (deriv base var))))) (define (install-exponentiation-extension) (put 'deriv '** deriv-exponentiation) 'done)
d
Solution 73d
The only changes needed are to the installation of the procedures into the generic dispatch table:
(put '** 'deriv deriv-exponentiation) (put '+ 'deriv deriv-sum ) (put '* 'deriv deriv-product)