Racket:用变量简化算术表达式

Racket: simplify arithmetic expressions with variables

我正在尝试实现一个功能

; (simplify expr)
;
; where expr is one of the following
; - a number
; - a symbol
; - a list of the form '(a operator b) where a and b are arithmetic expressions

该函数不应该尽可能地简化算术表达式,我只需要它来简化没有变量的子表达式:

示例:

(simplify '(3 + a))                  => '(3 + a)
(simplify '(((2 + (3 * 4)) * a) + 2) => '((14 * a) + 2)
(simplify '((2 + (3 - a)) * 2)       => '((2 + (3 - a)) * 2) 

我已经实现了一个计算算术表达式的函数:

(define (eval t)
  (cond
    [(number? t) t]
    [else ((cond
            [(equal? (second t) '+) +]
            [(equal? (second t) '-) -]
            [(equal? (second t) '*) *]
            [(equal? (second t) '/) /])
           (eval (first t)) (eval (third t)))])) 

这是我目前所拥有的,但除了它甚至无法正常工作这一事实之外,我想还有更好的方法。

(define (simplify t)
  (cond
    [(number? t) t]
    [(equal? 'a (first t)) `(,(first t) ,(second t) ,(simplify (third t))) ]
    [(equal? 'a (third t)) `(,(simplify (first t)) ,(second t) ,(third t)) ]
    [else ((cond
           [(equal? (second t) '+) +]
            [(equal? (second t) '-) -]
            [(equal? (second t) '*) *]
            [(equal? (second t) '/) /])
           (simplify (first t)) (simplify (third t)))]))

非常感谢任何帮助!

关键的见解是

 (number operation number) 

可以简化为

the result of evaluating (number operation number)

因此在 simplify 中添加一个检查模式 (number operation number) 的子句,然后使用您的 eval 函数查找结果。