Skip to content

Instantly share code, notes, and snippets.

@gideonite
Last active December 31, 2015 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gideonite/7936684 to your computer and use it in GitHub Desktop.
Save gideonite/7936684 to your computer and use it in GitHub Desktop.
Two calculators for arithmetic.
(defn eval-stack
[exp]
(match [exp]
[(_ :guard number?)] exp
[(_ :guard #{'+ '- '/ '*})] (eval exp) ;; hey Clojure, give me this operator...please!
[([ op left right] :seq)] ((eval-stack op) (eval-stack left) (eval-stack right))
:else "ERROR!"))
(comment
(eval-stack 1)
(eval-stack '+)
(eval-stack '(+ 1 1))
(eval-stack '(+ 1 (+ 2 3)))
(eval-stack '(+ 1 (/ 2 3))))
(defn halt [val]
(println "HALT!" val)
val)
(defn eval-cont
[exp k]
(println exp)
(match [exp]
[(_ :guard number?)] (k exp)
[(_ :guard #{'+ '- '/ '*})] (k (eval exp))
[([op left right] :seq)] (eval-cont op (fn [op]
(eval-cont left (fn [left]
(eval-cont right
(fn [right] (k (op left right))))))))
:else "ERROR!"))
(comment
(eval-cont '1 halt)
(eval-cont '+ halt)
(eval-cont '(+ 1 1) halt)
(eval-cont '(- 1 1) halt)
(eval-cont '(/ 1 2) halt)
(eval-cont '(* 2 1) halt)
(eval-cont '(+ (+ 1 2) (+ 3 (+ 4 5))) halt))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment