【发布时间】:2026-02-07 06:40:01
【问题描述】:
我有一个算法如下-
(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)))
为什么?
更新
我的最终代码是
(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 平行的东西快两倍。任何想法为什么?
顺便说一句,如果我从 r/fold 内容中删除 into [],那么我会得到 Execution time mean : 13.101313 ms。
【问题讨论】:
-
猜猜它会在没有
into的情况下给你这个结果,因为fold是惰性的,所以直到第一次使用结果才会发生缩减 -
我还认为由于并行处理基础设施开销,折叠方法要慢得多,这可能会被所提供任务的复杂性所抵消。在你的情况下,任务是微不足道的。此外,
transient方法是一个很好的优化,并且可能是最正确的。 -
感谢您的所有见解
标签: dictionary clojure mapreduce