Skip to content

Instantly share code, notes, and snippets.

@minhnhdo
Created April 25, 2013 12:26
Show Gist options
  • Save minhnhdo/5459320 to your computer and use it in GitHub Desktop.
Save minhnhdo/5459320 to your computer and use it in GitHub Desktop.
Infix to postfix expression conversion
(defun precedence (op)
(cond
((or (eq op '*) (eq op '/)) 20)
((or (eq op '+) (eq op '-)) 10)
(t 0)))
(defun infix->postfix (infix-exp)
"infix->postfix returns a postfix version of the infix expression passed to it. Currently, it does no error checking and does not support expressions with brackets."
(labels ((helper (acc op el iexp)
(cond
((numberp el) (helper (cons el acc) op (car iexp) (cdr iexp)))
((null iexp) (nconc (nreverse acc) op))
((or (null op) (> (precedence el) (precedence (car op))))
(helper acc (cons el op) (car iexp) (cdr iexp)))
(t (helper (cons (car op) acc) (cdr op) el iexp)))))
(helper () () (car infix-exp) (cdr infix-exp))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment