(ns rosettacode.parsing-rpn-calculator-algorithm
  (:require clojure.math.numeric-tower
            clojure.string
            clojure.pprint))

(def operators
  "the only allowable operators for our calculator"
  {"+" +
   "-" -
   "*" *
   "/" /
   "^" clojure.math.numeric-tower/expt})

(defn rpn
  "takes a string and returns a lazy-seq of all the stacks"
  [string]
  (letfn [(rpn-reducer [stack item] 
            (if (contains? operators item)
              (let [operand-1 (peek stack) 
                    stack-1 (pop stack)]   
                (conj (pop stack-1)
                      ((operators item) (peek stack-1) operand-1)))
              (conj stack (Long. item))))] 
    (reductions rpn-reducer [] (clojure.string/split string #"\s+")))) 

(let [stacks (rpn "3 4 2 * 1 5 - 2 3 ^ ^ / +")] 
  (println "stacks: ")
  (clojure.pprint/pprint stacks)
  (print "answer:" (->> stacks last first)))