我正在编写一个小程序来计算以列表形式表示的表达式的简单导数,即2x^2
表示为(* 2 (exp x 2))
,我定义了以下函数:
;; derivative of a constant is 0
(define (diff-constant x E) 0)
;; computes derivative of E with respect to x where E can only be of the form
;; (+ x x ...)
(define (diff-sum x E)
(cond ((or (not (list? E)) (null? E)) 0)
((eq? (car E) x) (+ 1 (diff-sum x (cdr E))))
(else (diff-sum x (cdr E)))))
;; computes derivative of E with respect to x where E can only be of the form
;; (* x y)
(define (diff-product x E)
(cond ((and (eq? x (cadr E)) (eq? x (caddr E))) (list '* 2 x))
((eq? x (cadr E)) (list (caddr E)))
((eq? x (caddr E)) (list (cadr E)))
(else 0)))
;; computes derivative of E with respect to x where E can only be of the form
;; (expt x y) which is x^y
(define (diff-expt x E)
(cond ( not (eq? x (cadr E)) 0)
((eq? 1 (caddr E)) 0)
((eq? 2 (caddr E)) (cadr E))
(else (list '* (caddr E) (list 'expt x (- (caddr E) 1))))))
我还有一个调度表定义为:
;; Dispatch Table of supported operators.
(define diff-dispatch
(list (list '+ diff-sum)
(list '* diff-product)
(list 'expt diff-expt)
))
我正在尝试编写一个函数,该函数diff
采用一个方程E
(以列表形式)并计算相对于的导数x
并使用调度表调用返回结果的预定义函数
这是我到目前为止所拥有的,但我无法弄清楚其余的
;; Differentiate expression E with respect to x.
(define (diff x E)
(cond ((number? E) (diff-constant x E))
;; insert code here to handle the other base case - variables
...
(else ; insert code here to lookup the appropriate function in the
; dispatch table based on the operator in the expression,
; then call that function to differentiate the expression
(diff-func x E))))))
例如:(diff 'x '(+ x (* x x)))
应该评估为(+ 1 (+ (* 1 (* x)) (* x 1)))
(即 1 + x + x)