[英]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.