Encapsulation in Clojure


/ Published in: Lisp
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.