表达树评估

时间:2011-04-14 06:13:09

标签: scheme expression-trees

我正在尝试评估表达式树。这是我的代码:

(define (eval-tree expr-tree)
  (eval-treeaux eval-tree expr-tree))

(define (eval-treeaux f expr-tree)
  (if (null? expr-tree)
      0
      (cond ((equal? '+ (operator expr-tree)) (+ (left-op expr-tree) (right-op expr-tree)))
            ((equal? '- (operator expr-tree)) (- (left-op expr-tree) (right-op expr-tree)))
            ((equal? '* (operator expr-tree)) (* (left-op expr-tree) (right-op expr-tree)))
            ((equal? '/ (operator expr-tree)) (/ (left-op expr-tree) (right-op expr-tree)))
            (else (f eval-treeaux expr-tree)))))

当我运行此(eval-tree '((6 * 3) + (4 - 2)))时,它会给我这个错误:

+: expects type <number> as 1st argument, given: (6 * 3); other arguments 
   were: (4 - 2)

谁能告诉我问题是什么以及如何解决?


这是我的新代码:

(define (eval-tree expr-tree)
  (if (null? expr-tree)
      0
      ((eval-treeaux eval-tree (car expr-tree)) (eval-tree (cdr expr-tree)))))

(define (eval-treeaux f expr-tree)
  (cond ((null? expr-tree) '())
        ((not (isExpression expr-tree)) (list expr-tree))
        (else (cond ((equal? '+ (operator expr-tree)) (+ (left-op expr-tree) (right-op expr-tree)))
                    ((equal? '- (operator expr-tree)) (- (left-op expr-tree) (right-op expr-tree)))
                    ((equal? '* (operator expr-tree)) (* (left-op expr-tree) (right-op expr-tree)))
                    ((equal? '/ (operator expr-tree)) (/ (left-op expr-tree) (right-op expr-tree)))
                    (else (f eval-treeaux expr-tree))))))

但是,当我运行此(eval-tree '((6 * 3) + (4 - 2)))时,我收到此错误:

procedure application: expected procedure, given: 2; arguments were: 0

我真的很困惑。有人可以帮我吗? 感谢

1 个答案:

答案 0 :(得分:1)

表达式((6 * 3) + (4 - 2))似乎由2个子表达式组成:

 (6 * 3)  ; e_1
 (4 - 2)  ; e_2

在评估父表达式之前,您需要递归计算子表达式。