On 12/12/12 00:16, Mark Engelberg wrote:
I would much prefer to have some sort of core function that serves as a polymorphic constructor. This way users don't need to require the concrete implementations individually.

I faced the same sort of issue a couple of months ago. Just like you, I wanted end-users to be able to instantiate their own records via a polymorphic function in the core ns. In other words, I wanted a way of instantiating records by passing only the record name (fully qualified of course) and whatever parameters the constructor expects. If i understand correctly this is what you're after yes?

There is a simple way of doing this but it is very very slow. Basically you need to resort to reflection...Chris Houser had posted such a record-factory fn on StackOverflow a while back. Here it is:

(defn record-factory [recordname]
(let [recordclass ^Class (resolve (symbol recordname))
max-arg-count (apply max (map #(count (.getParameterTypes ^java.lang.reflect.Constructor %))
(.getConstructors recordclass)))
args (map #(symbol (str "x" %)) (range (- max-arg-count 2)))]
(eval `(fn [~@args] (new ~(symbol recordname) ~@args)))))

even though i was very excited at the time i saw this, I later decided that it's not worth the performance cost for my use-case.

Jim

--
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

Reply via email to