使用reduce查找最大值

use*_*764 2 clojure

新的clojure与java背景.我有下表,需要将表转换为哈希映射,将产品映射到销售额最高的城市.例如,输出应如下所示:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
Run Code Online (Sandbox Code Playgroud)

这产生了结果:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
Run Code Online (Sandbox Code Playgroud)

我如何比较每个城市的销售情况,并且只保留销售额最高的城市名称?对此非常艰难.谢谢

lee*_*ski 8

max-keyclojure.core中有一个方便的功能,非常适合这种情况:

(defn process [table]
  (let [parseDouble #(Double/parseDouble (clojure.string/replace % #"," ""))]
    (->> table
         (group-by :product)
         (map (comp (juxt :product :city)
                    (partial apply max-key (comp parseDouble :sales))
                    val))
         (into {}))))

user> (process table)
;;=> {"Pencil" "Toronto", "Bread" "Ottawa"}
Run Code Online (Sandbox Code Playgroud)

关键是该(partial apply max-key (comp parseDouble :sales))部分查找组中的记录,具有最大解析的销售价值.