On Fri Mar 18 18:33 2011, Sunil S Nandihalli wrote: > I wanted to define a bunch of types which were mutable to be used in > defining a cyclic data structure. So, I wrote the following macro... > > … code sample … > > although not idiomatic clojure .. thought some of you may find it useful. > Sunil.
Is there some reason you chose to use mutable members instead of one of
Clojure's concurrency primitives? From your example, it doesn't seem
like interop is the reason, given that your mutators will be called
something similar to ‘y__BANG__’.
Also, given that you are defining both a protocol and a type where the
protocol doesn't seem like it really serves as an abstraction, perhaps
you would be better served with defrecord or just a plain old
map/struct.
Here's an example using maps:
(defn new-node []
{:prev (atom nil)
:next (atom nil)})
(defn attach-next! [node next-node]
(reset! (:next node) next-node))
(defn next-node [node]
@(:next node))
This approach allows you to do some things you can't do with volatile
mutables, such as an atomic compare and set operation:
(defn attach-next! [node next-node]
(compare-and-set! (:next node) nil next-node))
This function will only attach a next node if there is no next node
already.
Sincerely,
Daniel Solano Gómez
pgpkZ2DiLxE8A.pgp
Description: PGP signature
