gpt4 book ai didi

Clojure:动态构造基于变量的函数?

转载 作者:行者123 更新时间:2023-12-01 06:14:51 24 4
gpt4 key购买 nike

对于以下数据:

(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

我有两个问题要解决:

  1. 如何让选择器成为一个函数?
  2. 如何动态构建这种基于函数的坐标?

感谢您的指点和帮助!

我也猜想使用宏也可以做到这一点?

还是我使用了过于复杂的方法来实现我的目标?

最佳答案

只需直接调用 juxt 来创建您的函数,并定义选择器来保存该函数:

(def selector (juxt #(nth % 1) #(nth % 3)))

要使其动态化,创建一个函数创建函数:

(defn make-selector [& indexes] (apply juxt (map (fn[i] #(nth % i)) indexes)))

REPL 示例:

core> (def occurrence-data '(["John" "Artesyn" 1 31.0] ["Mike" "FlexPower" 2 31.0] ["John" "Eaton" 1 31.0]))
#'core/occurrence-data
core> (def selector (juxt #(nth % 1) #(nth % 3)))
#'core/selector
core> (group-by selector occurrence-data)
{["Artesyn" 31.0] [["John" "Artesyn" 1 31.0]], ["FlexPower" 31.0] [["Mike" "FlexPower" 2 31.0]], ["Eaton" 31.0] [["John" "Eaton" 1 31.0]]}
core> (group-by (make-selector 0 1 2) occurrence-data)
{["John" "Artesyn" 1] [["John" "Artesyn" 1 31.0]], ["Mike" "FlexPower" 2] [["Mike" "FlexPower" 2 31.0]], ["John" "Eaton" 1] [["John" "Eaton" 1 31.0]]}

关于Clojure:动态构造基于变量的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25560161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com