Contents    Page-10    Prev    Next    Page+10    Index   

Executing RPN


(defun execute-rpn (rpn)
  (let (stack rhs)
    (dolist (item rpn)
      (if (numberp item)
          (push item stack)
          (progn (setq rhs (pop stack))
                 (push (if (unaryp item)
                           (funcall item rhs)
                           (funcall item
                                    (pop stack)
                                    rhs))
                       stack))))
    (pop stack) ))

(defun unaryp (x) (member x '(minus sqrt)))

(execute-rpn '(3 4 + 5 *))  =  35

(execute-rpn (sublis '((a . 1)
                       (b . -3)
                       (c . 2))
                     (tree-to-polish testx)))
  =  2.0