Clojure's Reference Types

6539ae86c7d8ddec66f3928beddad569?s=47 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.

6539ae86c7d8ddec66f3928beddad569?s=128

Nate Smith

January 20, 2015
Tweet

Transcript

  1. 4.
  2. 7.
  3. 8.

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

    wayne-gretzky) ;; => {:number 99 :position "C" :goals 46}
  4. 9.

    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}
  5. 11.
  6. 12.
  7. 13.
  8. 14.
  9. 16.
  10. 17.
  11. 22.

    wayne_gretzky = { number: 99, position: "C", goals: 45 }

    wayne_gretzky[:goals] += 1 wayne_gretzky # => { number: 99, position: "C", goals: 46 }
  12. 24.
  13. 25.

    (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}
  14. 26.

    (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}
  15. 27.
  16. 29.

    (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}
  17. 30.
  18. 32.

    (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}
  19. 33.

    (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}
  20. 35.
  21. 36.