Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map sequence of functions to a sequence

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.

like image 602
Hendekagon Avatar asked Dec 21 '22 17:12

Hendekagon


2 Answers

  • Pass 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.
  • Consider using vectors instead of quoted lists. Vectors stand out as "data" rather than "code", and you don't have to quote them.
  • Your example functions don't do what you want; both return 1. I suspect you meant #(+ % 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)
like image 165
Brian Carper Avatar answered Dec 26 '22 21:12

Brian Carper


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
like image 28
amalloy Avatar answered Dec 26 '22 21:12

amalloy