I have a sequence of records/classes, and I map over that sequence with new and expect to get a sequence of instances of those records/classes. I know new is a special form, but I was expecting Clojure to do The Right Thing in this case.
But this does not work:
(map new [SomeClass1 SomeClass2 SomeClass3])
Neither does this.
(map #(new %) [SomeClass1 SomeClass2 SomeClass3])
Similar code works in Factor.
{ SomeClass1 SomeClass2 SomeClass3 } [ new ] map
What would be the right way to do this in Clojure? (I expect it won’t involve Class.newInstance ugliness.)
Edit:
The following works, but is perhaps slower than necessary. (I don’t know for sure. I would appreciate some information on this.)
(map #(eval `(new ~%)) [SomeClass1 SomeClass2 SomeClass3])
Also I am looking for something more elegant.
because special-formes are well… special they are not first class and don’t compose as proper functions do, you can solve this with eval and macros:
a solution using eval:
and a version that takes arguments to the constructors:
and here is a macro example
The macro version is likely more efficient while the eval version is more flexible.