リスト形式で表される式の単純な導関数を計算する小さなプログラムを作成しています。つまり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))))))
例: (つまり、1 + x + x)(diff 'x '(+ x (* x x)))
と評価される必要があります。(+ 1 (+ (* 1 (* x)) (* x 1)))