Applying sequence of functions to a sequence of values
I want to pairwise apply a list of functions to a list of values.
Here's an example to illustrate.
user=> (defn a [f x] (f x))
#'user/a
user=> (map a [inc dec] '(98 8))
(99 7)
Notice I had to defi开发者_如何转开发ne a function a that takes a function and applies it to a value. Basically abstracting function application.
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))
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)
If you're willing to slightly modify the format of your values, things get a bit simpler:
user=> (map apply [inc dec] [[98] [8]])
(99 7)
It's necessary because apply
must have a seq as its last argument. This transformation ([98 8]
=> [[98] [8]]
) feels like a reasonable thing to do anyway, since otherwise you depend on the fact that the functions may only take one value apiece. It's of course trivial to do:
user=> (map list [98 8])
((98) (8))
Otherwise, Joost's mapping function #(%1 %2)
is as concise as you're going to get.
精彩评论