prgrammer
prgrammer

Reputation: 53

expression tree evaluation

I'm trying to evaluate an expression tree. Here is my code:

(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)))))

When I run this (eval-tree '((6 * 3) + (4 - 2))), it gives me this error:

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

Can anyone tell me what the problem is and how I can fix it?


Here is my new code:

(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))))))

But, when I run this (eval-tree '((6 * 3) + (4 - 2))), I get this error:

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

I'm really confused. Can anyone help me please? Thanks

Upvotes: 0

Views: 957

Answers (1)

cam
cam

Reputation: 14222

The expression ((6 * 3) + (4 - 2)) appears to be composed 2 subexpressions:

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

You need to recursively evaluate the subexpressions before you can evaluate the parent expression.

Upvotes: 1

Related Questions