Вопрос:

Clojure: returning a vector from an anonymous function

clojure anonymous-function

5614 просмотра

3 ответа

14721 Репутация автора

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.

Автор: Ralph Источник Размещён: 07.02.2011 12:57

Ответы (3)


25 плюса

88537 Репутация автора

Решение

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 %)])
Автор: mikera Размещён: 07.02.2011 01:03

23 плюса

32728 Репутация автора

You need to use vector function to do this:

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

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

Автор: Alex Ott Размещён: 07.02.2011 01:11

4 плюса

2377 Репутация автора

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

I would recommend the following as the best alternative:

#(vector (keyword %) (.getObject resultset %))
Автор: drcode Размещён: 07.02.2011 01:11
Вопросы из категории :
32x32