我正在尝试在 Chez 方案中创建一个符号派生函数。它运行良好(尚未进行简化):
(define (derive var expr)
;; var is the direction in which you would like to derive
(if (list? expr)
(case (car expr)
('+ (sum-rule var expr))
('- (sub-rule var expr))
('* (prod-rule var expr))
;; other rules
(else (atomic-rule var expr )))
(atomic-rule var expr)))
(define (atomic-rule var expr)
(if (list? expr)
expr
(if (eqv? var expr)
1
0)))
(define (sum-rule var expr)
(let ((args (cdr expr)))
`(+ ,@(map (lambda (e) (derive var e)) args))))
(define (sub-rule var expr)
(let ((args (cdr expr)))
`(- ,@(map (lambda (e) (derive var e)) args))))
(define (prod-rule var expr)
(let* ((args (cdr expr))
(f (car args))
(g (cadr args)))
`(+ (* ,f ,(derive var g))
(* ,g ,(derive var f)))))
我可以执行(derive 'x '(+ (* x x) (* x y)))
并得到(+ (+ (* x 1) (* x 1)) (+ (* x 0) (* y 1)))
正确的结果。但我还想以编程方式创建从这些表达式返回数值的函数。
我的尝试失败了:
(define (lambda-derive var expr)
(let ([derivative (derive var expr)])
(lambda (var) derivative)))
((lambda-derive 'x '(* x x)) 2) => (+ (* x 1) (* x 1)) ;; should be 4
(define-syntax lbd-macro
(lambda (context)
(syntax-case context ()
[(k expr var )
(with-syntax ([new-var (datum->syntax #'k (syntax->datum #'var))])
#'(lambda (new-var) expr))])))
((lbd-macro (derive 'x '(* x x)) x) 2) => (+ (* x 1) (* x 1)) ;; should be 4
我感觉我忽略了一些非常明显的东西。有人能提供一些启示吗?(是的,我知道这些尝试没有涵盖多变量情况)
==编辑==
我睡了一个坏觉并决定继续工作,我找到了与 @ignis volens 描述的类似的解决方案,尽管使用了哈希表并且更加黑客化:
(define (lambda-aux variables vals expr)
(let ((ht (make-eqv-hashtable (length variables))))
(for-each (lambda (k v) (hashtable-set! ht k v)) variables vals)
(let loop ((expr expr))
(if (list? expr)
(let ((op (car expr))
(args (map loop (cdr expr))))
(cons op args))
(let ((variable (hashtable-ref ht expr #f)))
(if variable
variable
(if (number? expr)
expr
(error "variable not found"))))))))
(define-syntax lambda-derive
(syntax-rules ()
[(_ expr var var* ...)
(lambda (var var* ...) (eval (lambda-aux '(var var* ...) (list var var* ...) (derive 'var 'expr) )))]))
可以像这样使用:
(define my-test-derivative
;;f(x,y) = x^2 + x * y
;;df/dx (x,y) = 2*x + y
(lambda-derive (+ (* x y) (* x x)) x y))
(my-test-derivative 2 2) => 6
(my-test-derivative 8 2) => 18
;; ...