我正在编写一个小程序来计算以列表形式表示的表达式的简单导数,例如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
的函数,它接受一个方程(以列表形式表示),并计算对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)