Last active
November 30, 2016 02:47
-
-
Save AndyStewart/5633595 to your computer and use it in GitHub Desktop.
Improved Clojure calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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