0
(defn sort-map-by-value
  "Given a map return a sorted map, in which the sort is done on the map's values, instead of keys.
   Takes a function as an input, which will be used  for sorting"
  [cf kf]
  (fn [m]
    (->> m
         map-invert
         (into (sorted-map-by #(cf (kf %1) (kf %2))))
         map-invert)))

(defn date-time-comparator
  "Predicate function for comparing two date-time's"
  [time1 time2]
  (before? time1 time2))

(defn get-time-value
  "Function for extracting the date-time from the value of the given map."
  [v]
  (-> v first :time))

(def sort-map-by-date (sort-map-by-value date-time-comparator get-time-value))

(sort-map-by-date {"3-19-2013" [{:time (date-time 2013 3 19 12 14 45)}]
                         "3-9-2013" [{:time (date-time 2013 3 9 16 46 49)}]
                         "2-25-2013" [{:time (date-time 2013 2 25 2 38 15)}]
                         "3-14-2013" [{:time (date-time 2013 3 14 7 19 23)}]
                         "2-8-2013" [{:time (date-time 2013 2 8 12 44 47)}]
                         })

我试图了解使用高阶函数的惯用模式是什么。专门针对返回函数的函数。第一个函数 sort-map-by-value,以 2 个 fns 作为参数并返回一个以 map 作为参数的函数。

上述函数也可以将这三个函数、2 个函数和映射作为参数。所以在这种情况下不需要创建一个返回另一个函数的函数。需要它的情况是什么。或者换句话说,引入返回函数的函数的惯用模式是什么?

4

2 回答 2

1

I agree with the previous response about partial. And then there's comp which takes multiple fn's as input and returns the composition of them as output.

Here's an example that might help, although the output isn't quite a fn. I wanted to have background threads repeatedly executing some tasks in regular intervals. Each background thread executes one specific task, but the task differs from one thread to the next. So it made sense to have a HOF that takes a fn representing the task to repeat and returns a Thread, where the Thread is created that performs the input fn incessantly. The input fn is made to execute non-stop inside the Thread by being wrapped within a repeatedly form.

partial is the most likely way in which a HOF where the input and output are both a single fn each. The example I gave is what happens when the input fn is needed only for its side effects, so there's no point for the HOF's output to be a fn, if there the HOF has an output at all.

于 2013-04-03T06:07:09.270 回答
1

如果函数也将地图作为参数,则可以使用部分函数应用程序来实现所示的示例。

基本上,返回函数的函数是部分应用程序的特定情况,即您不会将所有参数传递给函数,作为回报,您会得到一个函数,该函数将获取剩余的参数并执行原始函数。我个人喜欢使用部分应用程序使用partial或使用匿名函数来创建部分函数(例如:)#(map inc %)

为什么我们需要它们?一方面,当您使用函数组合进行编程时,它们充当粘合剂。例如:

您想编写一个函数,递增向量中的每个数字,然后将其反转。

您可以在没有函数组合的情况下编写它:

(defn foo [v]
   (reverse (map inc v)))

使用函数组合:

(def foo (comp reverse (partial map inc)))

这可能不是最好的例子,但我希望你能明白。

另一个例子可能是包装函数。他们将输入作为一个函数并返回另一个函数(它与原始函数具有相同数量的参数)并在执行原始函数之前或之后执行某些操作(例如:Ring 中间件)

于 2013-03-26T11:25:25.570 回答