【发布时间】:2016-10-17 16:35:33
【问题描述】:
我正在尝试实现一个功能
; (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)))]))
非常感谢任何帮助!
【问题讨论】:
标签: racket simplify arithmetic-expressions