[英]Clojure reducer/map not working
我有一个算法如下-
(defn max-of
[args]
(into [] (apply map #(apply max %&) args)))
效果很好。
(max-of [[1 7] [3 5] [7 9] [2 2]])
返回[7 9]
它基本上找到每个位置上的最大元素。 7是最大的第一个元素是集合,而9是最大的第二个元素。 但是,当尝试使用core.reducers
reducer/map
时,我得到了
CompilerException clojure.lang.ArityException: Wrong number of args (21) passed to: reducers/map
所以这行不通-
(defn max-of
[args]
(into [] (apply r/map #(apply max %&) args)))
为什么?
UPDATE
我的最终代码是
(defn max-of [[tuple & tuples]]
(into [] (r/fold (fn
([] tuple)
([t1 t2] (map max t1 t2)))
(vec tuples))))
在其上运行快速工作台可得出Execution time mean : 626.125215 ms
我有我之前写的另一种算法-
(defn max-fold
[seq-arg]
(loop [acc (transient []) t seq-arg]
(if (empty? (first t))
(rseq (persistent! acc))
(recur (conj! acc (apply max (map peek t))) (map pop t)))))
做同样的事情。 为此,我得到- Execution time mean : 308.200310 ms
,这是r / fold并行Execution time mean : 308.200310 ms
两倍。 有什么想法吗?
顺便说一句,如果我从r/fold
内容中删除into []
,那么我得到的Execution time mean : 13.101313 ms
。
r/map
需要[f]
或[f coll]
-因此您的apply
方法在这里不起作用
user=> (doc r/map)
-------------------------
clojure.core.reducers/map
([f] [f coll])
与
user=> (doc map)
-------------------------
clojure.core/map
([f] [f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])
为什么给出这个问题的答案。 因此,让我们回答下一个问题:“您想做什么?”
根据我对目标的了解(通过元组中的位置查找最大元素)并潜在地并行执行(当您尝试使用reducer时),这就是您必须要做的
(defn max-of [tuples]
(r/fold (fn
([] (first tuples))
([t1 t2] (map max t1 t2)))
((rest tuples)))
user> (max-of [[1 7] [3 5] [7 9] [2 2]])
(7 9)
(max-of [[1 2 3] [3 2 1] [4 0 4]])
(4 2 4)
user> (max-of [])
nil
user> (max-of [[1 2 3]])
[1 2 3]
甚至在销毁方面更好:
(defn max-of [[tuple & tuples]]
(r/fold (fn
([] tuple)
([t1 t2] (map max t1 t2)))
tuples))
更新:对于大数据,您应该对其进行优化并切换为使用向量
(defn max-of [[tuple & tuples]]
(r/fold (fn
([] tuple)
([t1 t2] (map max t1 t2)))
(vec tuples)))
user> (max-of (repeat 1000000 [1 2 3 4 5 6 7 8 9 10]))
(1 2 3 4 5 6 7 8 9 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.