算术表达式解析

时间:2016-03-20 16:17:11

标签: scheme racket

我想将算术表达式解析为表示为(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> *) +)

1 个答案:

答案 0 :(得分:1)

你错过了重复的基本情况(这里是else形式的cond):

(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