减少Clojure

时间:2014-07-29 22:41:11

标签: clojure

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

(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}

我不明白参数minthis的来源。似乎coll可能是隐式破坏的。

如何更好地了解此功能的作用?

1 个答案:

答案 0 :(得分:6)

Reduce期望函数成为它的第一个参数。这个函数有两个参数,第一个参数是“到目前为止的结果”,第二个参数是“用来改变它的数据”。在上面的例子中,reduce是一个函数,它接收到目前为止发现的最小的东西,并将下一个元素与之进行比较。然后它决定哪一个更小,并将其作为结果保存到目前为止。

(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)))

这两个中间还有一个可选参数,用于指定结果的初始值。如果省略此可选参数(如上例所示),则前两个参数用于生成结果中的第一个值。因此,reduce函数实际上被称为比输入集合中的元素数少一个时间。

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