Last active
December 13, 2015 18:09
-
-
Save NicMcPhee/4953346 to your computer and use it in GitHub Desktop.
Simple example of atoms and atomic updates based on an example from Chapter 4 of Programming Clojure by Emerick, et al.
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.age-person) | |
;; 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#)) | |
(def chris (atom {:name "Chris" :age 40 :wears-glasses? false})) | |
;; Note that because comp goes "right to left" we do the glasses check first | |
;; and *then* increment the age. That means that we'll first wear glasses at | |
;; age 46. | |
(defn age-person [person] | |
(swap! person (comp #(update-in % [:age] inc) | |
#(do (Thread/sleep (rand-int 100)) %) | |
#(assoc % :wears-glasses? (or (println "\tTrying when they are " (:age %)) | |
(:wears-glasses? %) | |
(>= (:age %) 45))) | |
))) | |
(wait-futures 10 (do | |
(age-person chris) | |
(println "Succeeded, now Chris is " @chris) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment