将功能序列应用于值序列 [英] Applying sequence of functions to a sequence of values
问题描述
我想将函数列表成对地应用于值列表。
I want to pairwise apply a list of functions to a list of values.
下面是一个示例。
user=> (defn a [f x] (f x))
#'user/a
user=> (map a [inc dec] '(98 8))
(99 7)
注意,我必须定义一个函数a,它接受一个函数并将其应用于值。基本上是抽象函数应用程序。
Notice I had to define a function a that takes a function and applies it to a value. Basically abstracting function application.
有没有更自然的方法?我真的很想使用map定义一个辅助函数。
Is there a more natural way to do this? I would really just like to use map with defining a helper function.
推荐答案
您始终可以内联匿名定义函数:
You can always define functions anonymously, inline:
(map (fn [f x] (f x)) [inc dec] '(98 8))
或更短,使用#()阅读器宏:
or shorter, using the #() reader macro:
(map #(%1 %2) [inc dec] '(98 8))
虽然这是一个很尴尬的用例,所以我怀疑您是否可以仅使用核心clojure或clojure.contrib将其简化为更短的内容,但是您可以轻松编写自己的抽象:
It's a fairly awkward use case though, so I doubt you can reduce it to something shorter using just core clojure or clojure.contrib, but you can easily write your own abstraction:
(defn mapfs [fs coll] (map #(%1 %2) fs coll))
(mapfs [inc dec] [98 8])
> (99 7)
这篇关于将功能序列应用于值序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!