数式パーサ
優先順位を数値で指定する方式の中置演算子の処理がちょっとわかったかも。
(use util.match) (define rule '((+ . 1) (- . 1) (* . 2) (/ . 2))) (define (prec op) (let ((n (assoc op rule))) (if n (cdr n) 0))) (define parse (match-lambda ((e1) e1) ((e1 o1 e2) (list o1 e1 e2)) ((e1 o1 e2 o2 e3 . es) (if (< (prec o1) (prec o2)) (parse (append (list e1 o1 (list o2 e2 e3)) es)) (parse (append (list (list o1 e1 e2) o2 e3) es))))))
実行結果
gosh> (parse '(1 * 2 + 3 / 4 * 5)) (+ (* 1 2) (* (/ 3 4) 5))
括弧とかの処理はどうやって入れようかな。