1

I wish to use clojure STM to store data for my application, but to have the the data structure invisibly 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?

yazz.com
  • 57,320
  • 66
  • 234
  • 385
  • I'm not sure if this is a duplicate or not: http://stackoverflow.com/questions/4522796/how-should-i-make-a-clojure-stm-program-persistent – Robert Harvey Dec 31 '10 at 08:07
  • in some ways it is a duplicate, yes. in this question i was trying to find out more about overloading clojure core functions – yazz.com Dec 31 '10 at 08:35

2 Answers2

2

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.

casphas
  • 21
  • 1
  • How would I override my clojure.core import to use this amended version in my code? – yazz.com Dec 31 '10 at 15:17
  • You wouldn't. This is how polymorphism works in clojure with datatypes and protocols. The `assoc` function remains the same for all "normal" maps - only when it is applied to your custom type will it use your implementation (dispatch on the type of the first argument). – casphas Dec 31 '10 at 16:08
  • I still don't understand, but I'll do some research on Clojure types and then come back to this. Thanks for your input – yazz.com Dec 31 '10 at 16:12
  • This is not a bad starting point: http://www.ibm.com/developerworks/java/library/j-clojure-protocols/index.html – casphas Dec 31 '10 at 16:17
1

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. :)

Alex Miller
  • 69,183
  • 25
  • 122
  • 167