On Tue, Apr 26, 2011 at 1:06 PM, Steve Miner <stevemi...@gmail.com> wrote: > Creating your own "Closed Map" type would be the object-oriented approach. > One downside is that a closed-map feels like a normal map, but can't be > safely substituted for most maps because of the booby-trap when using assoc > (etc.) with a new key. It doesn't really fulfill the map contract anymore. > You'll have to do some defensive copying if you need a normal map. > > I would like to suggest a functional approach as an alternative. It seems to > me that the concept of "closedness" is a matter of interpretation. It could > be determined by the functions manipulating the data. Sometimes you might > want to treat the data (map) as closed and other times you might not care, so > you just need to use the appropriate functions. > > If you create your closed maps with all the allowed keys (nil values as > appropriate), you just need to call contains? on any new key to make sure > it's allowed. You could do that in a pre-condition. For example: > > (defn assert-key [m k] {:pre [(contains? m k)]} k) > > (defn assoc-closed [m k v] > (assoc m (assert-key m k) v)) > > (defn get-closed [m k] > (get m (assert-key m k)))
+1 -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en