Clojure: returning a vector from an anonymous function

孤街醉人 提交于 2019-11-27 13:39:44

问题


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.


回答1:


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 %)])



回答2:


You need to use vector function to do this:

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

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




回答3:


Yeah, Clojure should really support a #[...] construct, just for this case.

I would recommend the following as the best alternative:

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


来源:https://stackoverflow.com/questions/4921566/clojure-returning-a-vector-from-an-anonymous-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!