15. Refs - Koans Walkthrough

This video introduces refs which let us store values, and mutate them in a coordinated, thread-safe way. Refs can only be mutated in dosync transaction.

Here is the 15_refs.clj source code:

(def the-world (ref "hello"))
(def bizarro-world (ref {}))

  "In the beginning, there was a word"
  (= __ (deref the-world))

  "You can get the word more succinctly, but it's the same"
  (= __ @the-world)

  "You can be the change you wish to see in the world."
  (= __ (do
          (dosync (ref-set the-world "better"))

  "Alter where you need not replace"
  (= __ (let [exclamator (fn [x] (str x "!"))]
           (alter the-world exclamator)
           (alter the-world exclamator)
           (alter the-world exclamator))

  "Don't forget to do your work in a transaction!"
  (= 0 (do __

  "Functions passed to alter may depend on the data in the ref"
  (= 20 (do
          (dosync (alter the-world ___))))

  "Two worlds are better than one"
  (= ["Real Jerry" "Bizarro Jerry"]
          (ref-set the-world {})
          (alter the-world assoc :jerry "Real Jerry")
          (alter bizarro-world assoc :jerry "Bizarro Jerry")

Clojure Koans Walkthrough in Light Table IDE

This screencast tutorial helps you learn the Clojure programming language. Experience the joy of Clojure in the Light Table IDE as we tour through the Clojure Koans, taking you all the way from Beginner to Intermediate to Advanced.

Clojure is a Lisp created by Rich Hickey that runs on the JVM, as an alternative to Java. ClojureScript can target the web browser environment, and node.js, by compiling down to JavaScript, using the Google Closure compiler. Clojure features immutability, functional programming, and being a Lisp, macros.