Last active
May 25, 2016 22:52
-
-
Save NicMcPhee/4953522 to your computer and use it in GitHub Desktop.
The initial simple characters example from Chapter 4 of Programming Clojure by Emerick, et al. I added a little ```sleep``` to ```loot``` because otherwise often Bilbo got all the loot.
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 examples.characters) | |
;; Based on an example from Chap 4 of Programming Clojure | |
;; by Emerick, et al | |
(defmacro futures | |
[n & exprs] | |
(vec (for [_ (range n) | |
expr exprs] | |
`(future ~expr)))) | |
(defmacro wait-futures | |
[& args] | |
`(doseq [f# (futures ~@args)] | |
@f#)) | |
(defn character | |
[name & {:as opts}] | |
(ref (merge {:name name :items #{} :health 500} opts))) | |
(def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50)))) | |
(def bilbo (character "Bilbo" :health 100 :strength 100)) | |
(def gandalf (character "Gandalf" :health 75 :mana 750)) | |
(defn loot [from to] | |
(dosync (when-let [item (first (:items @from))] | |
(Thread/sleep (rand-int 5)) | |
; Try changing alter to commute; which replacements work and why? | |
(alter to update-in [:items] conj item) | |
(alter from update-in [:items] disj item)))) | |
(wait-futures 1 | |
(while (loot smaug bilbo)) | |
(while (loot smaug gandalf))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment