2011-04-14 242 views
0

我試圖評估表達式樹。這裏是我的代碼:表達式樹評估

(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 

我真的很困惑。任何人都可以幫助我嗎? 感謝

+0

我同意下面的答案。一個單獨的問題:爲什麼你在空列表上歸零?另外,爲什麼你將這個函數分成eval-tree和eval-treeaux?另外,你爲什麼將eval-tree傳遞給eval-treeaux?這段代碼需要大量的清理工作! – 2011-04-14 17:40:40

回答

1

表達((6 * 3) + (4 - 2))似乎是由2子表達式:

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

您需要遞歸評估子表達式,然後才能評估父表達。

+0

這就是我認爲我在aux函數的else語句中所做的事情。我需要另一個遞歸函數嗎?我不確定遞歸表達式是什麼。 – prgrammer 2011-04-14 06:25:36

+1

@prgrammer:在'else'中做它是不夠的。你也必須爲'+',''''',''''的操作數做到這一點,儘管這種方法變得很難看。你會想要進入每個子分支,但重構乾淨地做。 – 2011-04-14 06:57:39