Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: returning a vector from an anonymous function

Tags:

I wrote a small anonymous function to be used with a map call. The function returns a vector containing a column name and column value from a SQL result set query.

Here is the function (input is the column name):

(fn [name] [(keyword name) (.getObject resultset name)]) 

This works fine, however when I tried to use a "simplified" version of the anonymous function, I got an error:

#([(keyword %) (.getObject resultset %)])  java.lang.IllegalArgumentException: Wrong number of args (0) passed to: PersistentVector 

Here is the map call:

(into {} (map (fn [name] [(keyword name) (.getObject resultset name)]) column-names)) 

Is it possible to use the simplified syntax for this function? If so, how?

Thanks.

like image 817
Ralph Avatar asked Feb 07 '11 12:02

Ralph


2 Answers

Your problem is that the simple syntax is trying to evaluate the vector as a function call.

You can insert an "identity" function to make it work, as this is just a simple function that will return the vector unchanged:

#(identity [(keyword %) (.getObject resultset %)]) 
like image 194
mikera Avatar answered Sep 23 '22 20:09

mikera


You need to use vector function to do this:

#(vector (keyword %) (.getObject resultset %)) 

P.S. there are also functions for maps, sets, etc.

like image 45
Alex Ott Avatar answered Sep 23 '22 20:09

Alex Ott