我試圖評估表達式樹。這裏是我的代碼:表達式樹評估
(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
我真的很困惑。任何人都可以幫助我嗎? 感謝
我同意下面的答案。一個單獨的問題:爲什麼你在空列表上歸零?另外,爲什麼你將這個函數分成eval-tree和eval-treeaux?另外,你爲什麼將eval-tree傳遞給eval-treeaux?這段代碼需要大量的清理工作! – 2011-04-14 17:40:40