The Program (115 Chars)
(defun rpn(e)(let((s()))(dolist(x e)(if(numberp x)(push x s)(push(eval(revers开发者_开发知识库e(list(pop s)(pop s)x)))s)))(car s)))
A simple test:
CL-USER> (rpn '(1 2 3 * + 4 2 / +))
And it returns 9
Anyone has some good ideas about writing an Infix-to-RPN program inside one single tweet? I failed. I can wrote that one in 235 chars.
Here is one in Clojure (88 chars):
(defn rpn [& e](reduce #(if (fn? %2)(let [[l r & m]%](cons (%2 r l) m))(cons %2 %))[]e))
And the un-golfed version:
(defn rpn [& expr]
(reduce (fn [stack op]
(if (fn? op)
(let [[l r & m] stack]
(cons (op r l) m))
(cons op stack)))
[]
expr))
精彩评论