我正在尝试实现一个功能
; (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)))]))
非常感谢任何帮助!
答案 0 :(得分:4)
关键的洞察力是
(number operation number)
可以简化为
the result of evaluating (number operation number)
因此,在简化中添加一个子句,检查模式(number operation number)
,然后使用eval
函数查找结果。