我是Clojure编程方面的新手。已经玩了一个星期了。我阅读了“”一书“Clojure编程”,在一遍又一遍地阅读之后,尝试在REPL中剖析这个函数,但不知道这个函数到底是如何工作的:
(defn reduce-by [key-fn f init coll]
(reduce (fn [summaries x]
(let [k (key-fn x)]
(assoc summaries k (f (summaries k init) x))))
{} coll))
我仍然无法理解assoc
部分:
(assoc summaries k (f (summaries k init) x))))
尤其是在(summaries k init)
。它看起来不像一个函数,因为summaries
被定义为一个映射。
该函数的用途如下
(def orders
[{:product "Clock", :customer "Wile Coyote", :qty 6, :total 300}
{:product "Dynamite", :customer "Wile Coyote", :qty 20, :total 5000}
{:product "Shotgun", :customer "Elmer Fudd", :qty 2, :total 800}
{:product "Shells", :customer "Elmer Fudd", :qty 4, :total 100}
{:product "Hole", :customer "Wile Coyote", :qty 1, :total 1000}
{:product "Anvil", :customer "Elmer Fudd", :qty 2, :total 300}
{:product "Anvil", :customer "Wile Coyote", :qty 6, :total 900}])
(reduce-by :customer #(+ %1 (:total %2)) 0 orders)
它会产生一个像下面这样的seq
;= {"Elmer Fudd" 1200, "Wile Coyote" 7200}
我很感激任何能向我解释的人。
谢谢
发布于 2014-01-02 18:16:40
好吧,看来我想通了。
因为映射也是函数,如果映射(summaries k init)
不包含键k
,则summaries
将返回k
的值。
愚蠢的我浏览和忘记。
https://stackoverflow.com/questions/20888944
复制相似问题