减少Clojure [英] Reduce in Clojure

查看:74
本文介绍了减少Clojure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下如何评估以下匿名函数吗?

Can someone please explain how the below anonymous function is evaluated?

(defn min-by [f coll] 
  (when (seq coll)
    (reduce (fn [min this]
        (if (> (f min) (f this)) this min))
      coll)))

(min-by :cost [{:cost 100} {:cost 36} {:cost 9}])
;=> {:cost 9}

我不明白 min 来自。好像coll正在隐式地被破坏。

I don't understand where the arguments min and this come from. It seems like coll is being implicitly destructured perhaps.

如何更好地理解此函数的作用?

How can I better understand what this function is doing?

推荐答案

Reduce期望函数是它的第一个参数。该函数有两个参数,第一个参数是到目前为止的结果,第二个参数是用于更改结果的数据。在上面的示例中,reduce采取的功能是接收迄今为止找到的最小的事物,并将其与下一个元素进行比较。然后,它决定它们中的哪一个较小,并保留至今为止的结果。

Reduce expects a function as it's first argument. This function takes two arguments where the first argument is "the result thus far" and the second argument is "the data with which to change it". In the above example reduce is taking a function that recieves the smallest thing found thus far, and the next element to compare it to. It then decides which of them is smaller and keeps it as the result thus far.

(defn min-by [f   ;; this if a function that will be passed the smallest value 
                  ;; yet found and called again with the current value. 
                  ;; the result of these two calls will decide which is the min.
              coll] 
  (when (seq coll)
    (reduce 

      ;; first arg to reduce: a function to add something to the result

      ;; this function will be called once for each of the elements in the
      ;; collection passed as the second argument
      (fn [min     ; the result thus far 
           this]   ; the next element to include in the result

        ;; here we decide which is smaller by passing each to the function f
        ;; that was passed to min-by and compare is results for each of them.
        (if (> (f min) (f this)) this min))

      ;; second arg to reduce: the collection to work on

      ;; each element in this collection will be one of the values of
      ;; the "this" argument to the function above
      coll)))

还有一个这两个参数中间的可选参数,用于指定结果的初始值。如果忽略此可选参数,如上例所示,则前两个参数用于在结果中生成第一个值。因此,实际上,归约函数的调用时间比输入集合中元素的数量少一个时间。

There is also an optional argument in the middle of these two that specifies the initial value for the result. If you omit this optional argument, as in the example above, then the first two arguments are used to generate the first value in the result. So the reducing function is actually called one less time than the number of elements in the input collection.

user> (defn print+ [& numbers] (println "called print+") (apply + numbers))
#'builder.upload/print+
user> (reduce print+ [1 2 3])
called print+
called print+
6
user> (reduce print+ 0 [1 2 3])
called print+
called print+
called print+
6

这篇关于减少Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆