;---------------------------------------------------------------------------- ; Original code and concept by Gordon Novak Jr. ; (http://www.cs.utexas.edu/users/novak) ; ; Some modifications by Yoonsuck Choe ; Thu Sep 11 11:41:03 CDT 2003 ; ; To test: ; ; 1. save as file deriv.lsp. ; ; 2. run lisp ; ; 3. enter ; ; (load "deriv.lsp") ; ; 4. test deriv ; ; (deriv '(+ x (+ x 3)) 'x) ; ; 5. test splus ; ; (splus 0 'x) ; ; 6. test derivplus ; ; (derivplus '(+ x (+ 2 x)) 'x) ; ; 7. All of the above will work, out of the box. ; Extend and test one function at a time as you write. ; ; First, modify derivplus by calling splus in derivplus. ; ; Then, test derivplus ; ; (derivplus '(+ x (+ x x)) 'x) ; ;---------------------------------------------------------------------------- ;---------------------------------------- ; deriv ;---------------------------------------- (defun deriv (expr var) (if (atom expr) (if (equal expr var) 1 0) (cond ((eq '+ (first expr)) ; PLUS (derivplus expr var)) ((eq '* (first expr)) ; MULT (derivmult expr var)) (t ; Invalid (error "Invalid Expression!")) ) ) ) ;---------------------------------------- ; deriv plus ;---------------------------------------- (defun derivplus (expr var) (list '+ (deriv (second expr) var) (deriv (third expr) var) ) ) ;---------------------------------------- ; splus ;---------------------------------------- (defun splus (x y) (if (numberp x) (if (numberp y) (+ x y) (if (zerop x) y (list '+ x y) ) ) (if (and (numberp y) (zerop y)) x (list '+ x y) ) ) )