【发布时间】:2014-08-29 00:56:01
【问题描述】:
对于以下数据:
(def occurrence-data '(["John" "Artesyn" 1 31.0] ["Mike" "FlexPower" 2 31.0] ["John" "Eaton" 1 31.0]))
我想要一个函数:
(defn visit-numbers
"Produce a map from coordinates to number of customer visits from occurrence records."
[coordinates occurrences]
(let [selector ??? ; a function that would be equivalent to (juxt #(nth % c1) #(nth % c2) ..), where c1, c2, ... are elements of coordinates
]
(group-by selector occurrences)
)
例如,对于坐标 = [1 3]
应该是
(group-by (juxt #(nth % 1) #(nth % 3)) occurrence-data)
我想应该可以吧?我尝试使用一些列表表达式,但还没有弄清楚。
我的以下实验:
(def selector (list 'juxt '#(nth % 1) '#(nth % 3)))
(group-by selector occurrence-data)
出现错误:
java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to clojure.lang.IFn
core.clj:6600 clojure.core/group-by[fn]
protocols.clj:143 clojure.core.protocols/fn
protocols.clj:19 clojure.core.protocols/fn[fn]
protocols.clj:31 clojure.core.protocols/seq-reduce
protocols.clj:48 clojure.core.protocols/fn
protocols.clj:13 clojure.core.protocols/fn[fn]
core.clj:6289 clojure.core/reduce
core.clj:6602 clojure.core/group-by
我有两个问题要解决:
- 如何让选择器成为一个函数?
- 如何动态构建这种基于函数的坐标?
感谢您的指点和帮助!
我也猜想使用宏也可以做到?
还是我使用了太复杂的方法来实现我的目标?
【问题讨论】:
标签: clojure higher-order-functions