首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >这个clojure表达式是做什么的(摘自O‘’Reilly的书)

这个clojure表达式是做什么的(摘自O‘’Reilly的书)
EN

Stack Overflow用户
提问于 2014-01-02 18:04:29
回答 1查看 125关注 0票数 0

我是Clojure编程方面的新手。已经玩了一个星期了。我阅读了“”一书“Clojure编程”,在一遍又一遍地阅读之后,尝试在REPL中剖析这个函数,但不知道这个函数到底是如何工作的:

代码语言:javascript
运行
复制
(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部分:

代码语言:javascript
运行
复制
(assoc summaries k (f (summaries k init) x))))

尤其是在(summaries k init)。它看起来不像一个函数,因为summaries被定义为一个映射。

该函数的用途如下

代码语言:javascript
运行
复制
(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

代码语言:javascript
运行
复制
;= {"Elmer Fudd" 1200, "Wile Coyote" 7200}

我很感激任何能向我解释的人。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-01-02 18:16:40

好吧,看来我想通了。

因为映射也是函数,如果映射(summaries k init)不包含键k,则summaries将返回k的值。

愚蠢的我浏览和忘记。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20888944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档