Skip to content

Instantly share code, notes, and snippets.

@AndyStewart
Last active November 30, 2016 02:47
Show Gist options
  • Select an option

  • Save AndyStewart/5633595 to your computer and use it in GitHub Desktop.

Select an option

Save AndyStewart/5633595 to your computer and use it in GitHub Desktop.
Improved Clojure calculator
(ns calculator.core
(:gen-class))
(def operators { "-" - "+" + "/" / "*" *})
(defn convert-to-number [value]
(let [n (read-string value)]
(if (number? n) n nil)))
(defn read-operator []
(println "Enter an operator")
(read-line))
(defn read-value []
(println "Enter value")
(convert-to-number (read-line)))
(defn execute-calculation [running-total selected-operator value]
((operators selected-operator) running-total value))
(defn calculator
([] (calculator 0))
([running-total]
(println (str "Current total " running-total))
(def new-total (execute-calculation running-total (read-operator) (read-value)))
(calculator new-total)))
(defn -main
"Run the calculator"
[& args]
(calculator))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment