Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Clojure's Reference Types

Nate Smith
January 20, 2015

Clojure's Reference Types

A short introduction to Clojure's reference types that I gave to the Clojure Toronto meetup.

Nate Smith

January 20, 2015
Tweet

More Decks by Nate Smith

Other Decks in Technology

Transcript

  1. wayne-gretzky ;; => {:number 99 :position "C" :goals 45} (score

    wayne-gretzky) ;; => {:number 99 :position "C" :goals 46}
  2. wayne-gretzky ;; => {:number 99 :position "C" :goals 45} (score

    wayne-gretzky) ;; => {:number 99 :position "C" :goals 46} wayne-gretzky ;; => {:number 99 :position "C" :goals 45}
  3. wayne_gretzky = { number: 99, position: "C", goals: 45 }

    wayne_gretzky[:goals] += 1 wayne_gretzky # => { number: 99, position: "C", goals: 46 }
  4. (def atomic-wayne-gretzky (atom {:position "C" :number 99 :goals 0})) (deref

    atomic-wayne-gretzky) ;; => {:position "C" :number 99 :goals 0} @atomic-wayne-gretzky ;; => {:position "C" :number 99 :goals 0}
  5. (def atomic-wayne-gretzky (atom {:position "C" :number 99 :goals 0})) (dothreads!

    (fn [] (swap! atomic-wayne-gretzky score)) :threads 100 :times 100) @atomic-wayne-gretzky ;; => {:position "C" :number 99 :goals 10000}
  6. (defn score-slowly [player] (Thread/sleep 5000) (update-in player [:goals] inc)) (send

    agent-gretzky score-slowly) @agent-gretzky ;; => {:position "C" :number 99 :goals 0} @agent-gretzky ;; => {:position "C" :number 99 :goals 0} ;; 5 seconds later... @agent-gretzky ;; => {:position "C" :number 99 :goals 1}
  7. (def gretzky-curr (ref {:position "C" :number 99 :goals 0})) (def

    gretzky-prev (ref @gretzky-curr)) @gretzky-curr ;; => {:position "C" :number 99 :goals 0} @gretzky-prev ;; => {:position "C" :number 99 :goals 0}
  8. (dothreads! (fn [] (dosync (ref-set gretzky-prev @gretzky-curr) (alter gretzky-curr score)))

    :threads 100 :times 100) @gretzky-prev ;; => {:position "C" :number 99 :goals 9999} @gretzky-curr ;; => {:position "C" :number 99 :goals 10000}