In Part 1, we used defrecords to create a vampire slayer named “Buffy” and a few vampires for her to kick around. Today we are going to use Buffy and her vampires to explore STM (Software Transactional Memory) in Clojure for managing state.
Recap
(defrecord Vampire [name, health]) (def vampire1 (Vampire. "Stu" 50)) (def vampire2 (Vampire. "Vance" 100)) (def vampire3 (Vampire. "Izzy" 75)) (defrecord Slayer [name, weapon]) (def kungfu 25) (def buffy (Slayer. "Buffy" kungfu)) (defn hit [vampire, hitpoints] (- (:health vampire) hitpoints)) ;vampires don't fight back but it takes time to kill them (def combat-time 20) (defn hit-vampire [vampire, slayer] (Thread/sleep (* combat-time 10)) (assoc vampire :health (hit vampire (:weapon slayer)))) (defn kill-vampire [vampire, slayer] (if (> (:health vampire) 1) (recur (hit-vampire vampire slayer) slayer) (assoc vampire :health 0))) Let’s take our vampires and stand them up in a line for Buffy to fight. We are also going to create a function that just has Buffy killing a vampire, rather then a generic slayer.
...