【发布时间】:2016-06-15 10:55:32
【问题描述】:
我实现了一个接受算术表达式并返回值的函数:
; an arithmetic expression (t) is one of the following:
; - a number
; - a list of the form '(a operator b) where a and b are arithmetic expressions
; arithmetic expression -> number
; computes the value of the arithmetic expression
(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)))]))
它工作得很好,但显然它不能接受常量。所以我想做的是扩展程序,使其适用于以下内容:
(eval '(1 + (3 * x)) (make-const 'x 3) -> 10
(eval '((3 - x) * y) ((make-const 'x 1) (make-const 'y 2)) -> 4
(eval '(1 + (y * x)) (make-const 'x 3) -> "error"
我的想法是定义一个结构:
(define struct const (symbol number))
(define (eval. t x)
(cond
[(number? t) t]
[(symbol? t) ???]
[else ((cond
[(equal? (second t) '+) +]
[(equal? (second t) '-) -]
[(equal? (second t) '*) *]
[(equal? (second t) '/) /])
(eval. (first t) lst) (eval. (third t) lst))]))
谁能告诉我我是否朝着正确的方向前进并给我一个提示?将不胜感激!
【问题讨论】:
标签: eval racket arithmetic-expressions