I was trying to experiment with Clojure Protocols and Records recently, and came up with a toy example to clarify my understanding of their usage in the context of developing a simple Stack Abstract Data Type.
For an excellent tutorial on utilizing protocols and records in Clojure btw – check out (http://kotka.de/blog/2010/03/memoize_done_right.html#protocols).
;; Stack example abstract data type using Clojure protocols and records
;; viksit at gmail dot com
;; 2010
(ns viksit.stack
(:refer-clojure :exclude ))
(defprotocol PStack
"A stack protocol"
(push "Push element into the stack")
(pop "Pop element from stack")
(top "Get top element from stack"))
(defrecord Stack
PStack
(push
(swap! coll conj val))
(pop
(let
(swap! coll rest)
ret))
(top
(first @coll)))
;; Testing
stack> (def s (Stack. (atom '())))
#'stack/s
stack> (push s 10)
(10)
stack> (push s 20)
(20 10)
stack> (top s)
20
stack> s
#:stack.Stack{:coll #<atom>}
stack> (pop s)
20
</atom>
More tutorial links on Protocols,
\ http://blog.higher-order.net/2010/05/05/circuitbreaker-clojure-1-2/
\ http://freegeek.in/blog/2010/05/clojure-protocols-datatypes-a-sneak-peek/
\ http://groups.google.com/group/clojure/browse\_thread/thread/b8620db0b7424712
--
If you have any questions or thoughts, don't hesitate to reach out. You can find me as @viksit on Twitter.