Posted By

narkisr on 08/13/09


Tagged

encapsulation clojure


Versions (?)

Encapsulation in Clojure


 / Published in: Lisp
 

URL: http://blog.thinkrelevance.com/2009/8/12/rifle-oriented-programming-with-clojure-2

Using closures in order to encapsulate access to data (in this case the counter is thread safe atom).

  1. (defn make-counter [init-val]
  2. (let [c (atom init-val)]
  3. {:next #(swap! c inc)
  4. :reset #(reset! c init-val)}))
  5.  
  6. (def c (make-counter 10))
  7. -> #'user/c
  8.  
  9. ((c :next))
  10. -> 11
  11.  
  12. ((c :next))
  13. -> 12
  14.  
  15. ((c :reset))
  16. -> 10

Report this snippet  

You need to login to post a comment.