Skip to content

Instantly share code, notes, and snippets.

@erdos
Created June 7, 2017 08:35
Show Gist options
  • Save erdos/8a081c0ebbf5e6f0d3c04f6714c574d6 to your computer and use it in GitHub Desktop.
Save erdos/8a081c0ebbf5e6f0d3c04f6714c574d6 to your computer and use it in GitHub Desktop.
Simple Reverse Polish Notation Calculator in Clojure
(defn rpn [s]
(first (reduce (fn [[s1 s2 & ss :as stack] op]
(case op
+ (cons (+ s1 s2) ss)
- (cons (- s1 s2) ss)
* (cons (* s1 s2) ss)
/ (cons (/ s1 s2) ss)
, (cons op stack)))
() (read-string (str \( s \))))))
@erdos
Copy link
Author

erdos commented Jun 7, 2017

this should also do it.

(defn rpn [s]
    (first (reduce (fn [[s1 s2 & ss :as stack] op]
                     (try (cons ((eval op) s1 s2) ss)
                          (catch Exception _ (cons op stack))))
                   () (read-string (str \( s \))))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment