CprS376 Schedule
CprS376 Class 6
CprS376 Class 8

Symbolic Data

Class 7 - Section 2.3



Contents

Symbolic-Differentiation
;;  symbolic-differentiation.ss

;  William E. Duncan cnd Chris Parrish
;  CS-326 / Functional Programming
;  September 11, 1998


;; the deriv program

(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))))
        (else
         (error "unknown expression type -- DERIV" exp))))


;; selectors, constructors and predicates
;; for algebraic expressions in which the 
;; operators + and * take only two arguments

;; the arithmetic expressions are assumed to 
;; be written in prefix notation

;; ;; cf. SICP, pages 146ff

(define (variable? e) 
  (symbol? e))

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

(define (sum? e)
  (and (pair? e) 
       (eq? (car e) '+)))

(define (addend e) 
  (cadr e))

(define (augend e)
  (caddr e))

(define (product? e)
  (and (pair? e) 
       (eq? (car e) '*)))

(define (multiplier e) 
  (cadr e))

(define (multiplicand e)
  (caddr e))

(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 ((or (=number? m1 0) (=number? m2 0)) 0)
        ((=number? m1 1) m2)
        ((=number? m2 1) m1)
        ((and (number? m1) (number? m2)) (* m1 m2))
        (else (list '* m1 m2))))

(define (=number? x y)
  (and (number? x) 
       (number? y)
       (= x y)))


;; Now we can differentiate sums and products 
;; of arithmetic expressions in which the
;; operators + and * take exactly two arguments

(deriv '(+ x 3) 'x)
; => 1


(deriv '(* x y) 'x)
; => y


(deriv '(* (* x y) (+ x 3)) 'x)
; => (+ (* x y) (* y (+ x 3)))

(deriv '(* (* x y) (+ x 3)) 'y)
; => (* x (+ x 3))


(deriv '(+ 3 (* 2 (+ x (* 4 y)))) 'x)
; => 2

(deriv '(+ 3 (* 2 (+ x (* 4 y)))) 'y)
; => 8

SICP Source Code

Programming Exercises

In class today we will continue our work on the following exercises from chapter 2: 1, 4, 5, 8, 10, 11, 19, 20, 21, 23, 24, 25, 26, 27, 58, 59, 60, 61, 67, 73, 87, 88, 89.