Created
March 6, 2014 20:54
-
-
Save kornysietsma/9399426 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
(def moneys {:nickel 5 :dime 10 :quarter 25 :dollar 100}) | |
(def prices {:a 65 :b 100 :c 150}) | |
(def initial-state | |
{:inserted-money [:nickel :dime] | |
:items {:a 15 :b 3} | |
}) | |
(defn in-stock? [state item] | |
(let [stock-level (item (:items state))] | |
(and (not (nil? stock-level)) (< 0 stock-level)))) | |
(defn add-money [state value] | |
(update-in state [:inserted-money] conj value)) | |
(defn balance [state] | |
(apply + (map moneys (:inserted-money state)))) | |
(defn without [state item] | |
(-> state | |
(update-in [:items item] dec) | |
(assoc :inserted-money []))) | |
(defn get-item [state item] | |
(let [item-value (item prices) | |
machine-balance (balance state) | |
in-stock (in-stock? state item)] | |
(if (and (<= item-value machine-balance) in-stock) | |
[(without state item) item] | |
[state nil]))) | |
(def machine (atom {:inserted-money [] | |
:items {:a 15 :b 3 :c 1}})) | |
(defn add-money! [value] | |
(swap! machine add-money value)) | |
(defn get-item-and-print-errors [state item] | |
(let [[new-state result] (get-item state item)] | |
(if (nil? result) | |
(println "FAIL - can't sell you a" (name item))) | |
new-state)) | |
(defn get-item! [item] | |
(swap! machine get-item-and-print-errors item)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment