How could I map each function in a sequence of functions to its corresponding value in a sequence of values ?:
(map '(sequence of functions) '(sequence of values))
the nth function in the function sequence should be applied to the nth value in the value sequence. sorry if i'm not very clear.
for example, say (def fns '(#(+ 1 %) #(- 1 %)) )
then (map (some-clever-function-of fns) '(0 0))
would produce (1 -1) because #(+ 1 %)
was mapped to the 1st 0 and #(- 1 %)
to the 2nd.
map
more than one sequence of arguments, and it'll do exactly what you want. (map f seq1 seq2)
expects f
to be a function that takes two arguments; map
will pas the first element of seq1
and the first element of seq2
to f
, then the second element of each, etc. As soon as any seq of arguments runs out, map
stops, so this works with infinite sequences as well.#(+ % 1)
and #(- % 1)
. Both of these are in clojure.core
, called inc
and dec
respectively.So:
user> (map (fn [f x] (f x))
[inc dec]
[0 0])
(1 -1)
Or:
user> (map #(%1 %2) [inc dec] [0 0])
(1 -1)
I usually define an invoke
function that acts like apply
but without the list-collapsing:
(defn invoke [f & args]
(apply f args))
(map invoke [+ -] [1 2] [3 4])
(4 -2) ; 1 + 3, 2 - 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With