Last active
June 30, 2024 14:40
-
-
Save trikitrok/376e3a44f1fc6c6826df to your computer and use it in GitHub Desktop.
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 rpn.core | |
| [:use [clojure [string :only [split]]]]) | |
| (defn parse-int [s] | |
| (Integer/parseInt (re-find #"\A-?\d+" s))) | |
| (defn parse [expression] | |
| (let | |
| [operators {"+" + "-" - "*" * "/" quot} | |
| parse-token | |
| (fn [token] | |
| (if (contains? operators token) | |
| (get operators token) | |
| (parse-int token)))] | |
| (map parse-token | |
| (split expression #"\s")))) | |
| (defn process-symbol [stack symbol] | |
| (if (number? symbol) | |
| (conj stack symbol) | |
| (conj (pop (pop stack)) | |
| (apply symbol (take-last 2 stack))))) | |
| (defn evaluate [expression] | |
| (peek | |
| (reduce | |
| process-symbol | |
| [] | |
| (parse expression)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment