;;; deriv.scm ;;; ;;; Symbolic differentiation ;;; ;;; CS 313 (define (constant? x) (number? x)) (define (variable? x) (symbol? x)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eqv? v1 v2))) ; creates sum expression; does some simplification (define (make-sum a1 a2) (cond ((and (number? a1) (number? a2)) (+ a1 a2)) ((eqv? a1 0) a2) ((eqv? a2 0) a1) ((equal? a1 a2) (make-product 2 a1)) (else (list '+ a1 a2)))) ; creates product expression; does some simplification (define (make-product m1 m2) (cond ((and (number? m1) (number? m2)) (* m1 m2)) ((eqv? m1 0) 0) ((eqv? m1 1) m2) ((eqv? m2 0) 0) ((eqv? m2 1) m1) (else (list '* m1 m2)))) (define (sum? x) (and (pair? x) (eqv? (car x) '+) (= (length x) 3))) ; can only handle 2 arguments (define (product? x) (and (pair? x) (eqv? (car x) '*) (= (length x) 3))) ; can only handle 2 arguments (define (arg1 exp) (cadr exp)) (define (arg2 exp) (caddr exp)) ; compute derivative of 'exp' with respect to variable 'var' (define (deriv exp var) (cond ((constant? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (arg1 exp) var) (deriv (arg2 exp) var))) ((product? exp) (make-sum (make-product (arg1 exp) (deriv (arg2 exp) var)) (make-product (deriv (arg1 exp) var) (arg2 exp)))) (else (error "ERROR: cannot handle expression")))) ; the current scheme environment (need for 'eval') (define current-env (the-environment)) ; evaluates symbolic expression 'exp' by substituting 'val' for 'x' (define (compute exp val) (let ((f (list 'lambda '(x) exp))) (eval (list f val) current-env))) ; example use: ; (define g '(* x (* x x))) ; (compute g 4) ; 64 ; (compute (deriv g 'x) 5) ; 75