【问题标题】:Racket: simplify arithmetic expressions with variablesRacket:用变量简化算术表达式
【发布时间】: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


    【解决方案1】:

    关键的见解是

     (number operation number) 
    

    可以简化为

    the result of evaluating (number operation number)
    

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

    【讨论】:

    • 谢谢!我写了一个函数 (match-pattern?t) (因为我不能使用 match 函数)检查列表中的模式(数字操作号),但如果它返回 #true,它会评估整个列表(什么由于变量而返回错误),而不仅仅是 (num op num) 表达式。你能给我一个提示吗? (define (simplify t) (cond [(number?t) t] [(symbol?t) t] [(match-pattern?t) (eval t)] [else t]))
    • 您需要一个额外的子句来处理(expression op expression) 的情况并产生(简化表达式操作简化表达式)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2015-10-27
    • 2011-01-25
    • 1970-01-01
    • 2014-09-16
    相关资源
    最近更新 更多