A while ago I wrote a short MUD which had to keep track of a changing
group of players, and other data. Retrospectively I've developed a
helper which can update in place any mutable map, handles nested
access, and behaves like assoc on immutables.
It allows usage like so:
; set up a mutable map of mutable players - tongue twister
(def players (ref nil))
(mset players "tim" (ref {:str 5 :con 5}))
(mset players "tom" (ref {:str 7 :con 2}))
; change some attributes
(mset players "tim" :str 6)
(mset players "tim" :con 4)
(mset players "tim" :friend (@players "tom"))
; results in pretty much what you might expect
(println "tim:" @(@players "tim"))
(println "tom:" @(@players "tom"))
(println "tim's friend" @((@players "tim") :friend))
tim: {:str 6, :con 4}
tom: {:str 7, :con 2}
tim's friend {:str 7, :con 2}
http://groups.google.com/group/clojure/web/helper.clj
Working on the deletion side I ran into a bit of a block when trying
to nil refs that were being removed:
; dissoc versions
(defmulti mdel (fn [m & args] (class m)))
(defmethod mdel clojure.lang.Ref [v]
(dosync (ref-set v nil)))
(defmethod mdel clojure.lang.Ref [m k & more]
(if more
(apply mdel (@m k) more)
(dosync (mdel (@m k))
(ref-set m (dissoc @m k))))
m)
(mdel (ref 5))
-> arity exception
I'm not sure why... I suspect it is something obvious I'm overlooking.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---