my attempt to do the exercises in sicp.

Monday, July 21, 2008

sicp exercise 2.56



;; Exercise 2.56.  Show how to extend the basic differentiator to handle more kinds of expressions. For instance, implement the differentiation rule



;; by adding a new clause to the deriv program and defining appropriate procedures exponentiation?, base, exponent, and make-exponentiation. (You may use the symbol ** to denote exponentiation.) Build in the rules that anything raised to the power 0 is 1 and anything raised to the power 1 is the thing itself.

(define (variable? exp) (symbol? exp))
(define (same-variable? v1 v2)
  (and (variable? v1) (variable? v2) (eq? v1 v2)))


(define (sum? exp) (and (pair? exp) (eq? '+ (car exp))))
(define (addend exp) (cadr exp))
(define (augend exp) (caddr exp))

(define (product? exp) (and (pair? exp) (eq? '* (car exp))))
(define (multiplicand exp) (cadr exp))
(define (multiplier exp) (caddr exp))

(define (exponentiation? exp) (and (pair? exp) (eq? '** (car exp))))
(define (base exp) (cadr exp))
(define (exponent exp) (caddr exp))

(define (make-sum x y)
  (cond ((and (number? x) (= x 0)) y)
        ((and (number? y) (= y 0)) x)
((and (number? x) (number? y)) (+ x y))
(else (list '+ x y))))

(define (make-product x y)
  (cond ((and (number? x) (= x 1)) y)
        ((and (number? y) (= y 1)) x)
        ((and (number? x) (= x 0)) 0)
        ((and (number? y) (= y 0)) 0)
((and (number? x) (number? y)) (* x y))
(else (list '* x y))))

(define (make-exponentiation base exponent)
  (cond ((and (number? exponent) (= exponent 0)) 1)
        ((and (number? exponent) (= exponent 1)) base)
(else (list '** base exponent))))

(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 (multiplicand exp)
                  (deriv (multiplier exp) var))
            (make-product (multiplier exp)
                  (deriv (multiplicand exp) var))))
        ((exponentiation? exp)
       (make-product (exponent exp)
           (make-product
             (make-exponentiation (base exp) (- (exponent exp) 1))
     (deriv (base exp) var))))
        (else (error "ERROR-" exp))))

(display (deriv '(+ x 3) 'x)) (newline)
(display (deriv '(* (* x y) (+ x 3)) 'x)) (newline)
(display (deriv '(** x 4) 'x)) (newline)

(display (deriv (deriv '(** x 4) 'x) 'x)) (newline)
;; (* 4 (* 3 (** x 2))) ;; needs improvement. should be (* 12 (** x 2))




No comments: