Problem 8: Derive (optional, 0 pts)
The following problems develop a system for symbolic differentiation of algebraic expressions. The derive
Scheme procedure takes an algebraic expression and a variable and returns the derivative of the expression with respect to the variable. Symbolic differentiation is of special historical significance in Lisp. It was one of the motivating examples behind the development of the language. Differentiating is a recursive process that applies different rules to different kinds of expressions.
; derive returns the derivative of EXPR with respect to VAR
(define (derive expr var)
(cond ((number? expr) 0)
((variable? expr) (if (same-variable? expr var) 1 0))
((sum? expr) (derive-sum expr var))
((product? expr) (derive-product expr var))
((exp? expr) (derive-exp expr var))
(else 'Error)))
To implement the system, we will use the following data abstraction. Sums and products are lists, and they are simplified on construction:
; Variables are represented as symbols
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
; Numbers are compared with =
(define (=number? expr num)
(and (number? expr) (= expr num)))
; Sums are represented as lists that start with +.
(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 (sum? x)
(and (list? x) (eq? (car x) '+)))
(define (first-operand s) (cadr s))
(define (second-operand s) (caddr s))
; Products are represented as lists that start with *.
(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 (product? x)
(and (list? x) (eq? (car x) '*)))
; You can access the operands from the expressions with
; first-operand and second-operand
(define (first-operand p) (cadr p))
(define (second-operand p) (caddr p))
Note that we will not test whether your solutions to this question correctly apply the chain rule. For more info, check out the extensions section.