clojure无法通过map to list应用函数

时间:2017-05-05 12:06:19

标签: clojure

我似乎很难理解如何使用clojure map。我有一个名为in-grids的对象列表,我不想使用方法getCoordinateSystem。我想列表中的对象是一些Java类是很重要的。当我在clojure中直接定义函数时,map可以正常工作。

这有效:

(.getCoordinateSystem (first in-grids))

但不是这个

(map .getCoordinateSystem in-grids)

错误是:java.lang.RuntimeException: Unable to resolve symbol: .getCoordinateSystem in this context

我可能错过了一些非常明显的东西,但具体到底是什么?

3 个答案:

答案 0 :(得分:5)

如果您有表格

(map f sequence)

然后f应引用IFn的实例,然后为sequence的每个元素调用该实例。

.是一种特殊形式,.getCoordinateSystem未引用IFn个实例。

(.getCoordinateSystem (first in-grids))

相当于

(. (first in-grids) (getCoordinateSystem))

您可以直接构造函数值,例如

(map #(.getCoordinateSystem %) in-grids)

答案 1 :(得分:2)

map函数的另一个选择通常是for的替代选择:

(for [grid in-grids]
  (.getCoordinateSystem grid))

以这种方式使用formap具有相同的效果,但在处理的“一次性项目”性质上更明确一些。此外,由于您直接调用Java函数getCoordinateSystem,因此无需将其包装在Clojure函数文本中。

答案 2 :(得分:0)

作为Lee的答案的替代方案,有memfn宏,它扩展为类似于答案的代码。

(map (memfn getCoordinateSystem) in-grids)

(macroexpand '(memfn getCoordinateSystem))
;=> (fn* ([target56622] (. target56622 (getCoordinateSystem))))
相关问题