开发者

overloading a clojure hash map in an STM transaction

I wish to use clojure STM to store data for my application, but to have the the data structure i开发者_运维问答nvisibly persist the structure to a datastore. how can I extend the built in types with my own functionality so that the user of the API is unaware.

note that I wish to use all then standard clojure calls to manipulate the data structures, thereby making the caller of the API unaware. is this even possible?


Not sure whether this is the way, but you can extend the interfaces (protocols) from clojure.lang. Here is a very minimal example of adding a side effect (as you would need to) to the assoc function of a map.

(deftype LolMap [m]
  clojure.lang.IPersistentMap
  (assoc [this k v] (do (println (str k " CAN HAS " v "!")) 
                        (LolMap. (assoc m k v))))
  clojure.lang.Seqable
  (seq [this] (seq m)))

The type just wraps a real map, you would have to provide proper implementations for all the interfaces involved (IPersistentMap and Seqable are the bare minimum to be able to instantiate and print an instance in the REPL). For all read operations it should be sufficient to simply pass through the real map functions as the implementation.


deftype is designed to create new data structure-y type things but I'm not sure you can achieve these goals until more of the Clojure-in-Clojure and protocol-izing of the internals of Clojure occur. I'd love to be wrong though. :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜