2016-03-20 135 views
0

我想將算術表達式解析爲一個二叉樹,表示爲(list left right value)。這是我的代碼:算術表達式解析

(define (parse exp) 
(let loop ([e exp]) 
    (cond 
    ((and (list? e) (or (not (null? (car e))) (not (null? (caddr e))))) 
     (list (loop (car e)) (loop (caddr e)) (cadr e)))))) 

(parse '(1 + (2 * 3))) 

結果是這樣,我不知道從void出現在哪裏。

'(#<void> (#<void> #<void> *) +) 

回答

1

你錯過了recusion的基本情況(這裏它是elsecond形式):

(define (parse exp) 
    (let loop ([e exp]) 
    (cond 
     ((and (list? e) (or (not (null? (car e))) (not (null? (caddr e))))) 
     (list (loop (car e)) (loop (caddr e)) (cadr e))) 
     (else e)))) 

測試:

> (parse '(1 + (2 * 3))) 
'(1 (2 3 *) +) 

#<void>是「下降的結果通過「cond表(即沒有條件匹配,並且沒有else):

> (void? (cond)) 
#t