Say I have a group of functions:
f1[a_] := a * -1;
f2[a_] := a * 100;
f3[a_] := a / 10.0;
and some data in a list:
data := Range[1, 20];
I would like to apply this group of functions to the data: the first function applied to the first item of data, the second to the second, and so on. Because there are more data elements than there are functions, the first function is also applied to the fourth data element, and so on.
A simple work-round is this:
Flatten[{f1[#[[1]]], f2[#[[2]]], f3[#[[3]]]} & /@ Partition[data, 3]]
giving
{-1, 200, 0.3, -4, 500, 0.6, -7, 800, 0.9, -10, 1100, 1.2, -13, 1400,
1.5, -16, 1700, 1.8}
but this isn't an ideal solution: the slots have been 'hard-wired', and it wouldn't be possible to modify the list of functions easily.
Is there a Map
-related function that could do this elegantly? I've not been able to discover it yet.
(This is a toy example, of course!)
Answer
Here's how you can do it in a simple way:
functionMap[funcs_List, data_] := Module[{fn = RotateRight[funcs]},
First[(fn = RotateLeft[fn])][#] & /@ data]
Use it as:
functionMap[{f1, f2, f3}, Range[20]]
(* {f1[1], f2[2], f3[3], f1[4], f2[5], f3[6], f1[7], f2[8], f3[9], f1[10],
f2[11], f3[12], f1[13], f2[14], f3[15], f1[16], f2[17], f3[18], f1[19], f2[20]} *)
Comments
Post a Comment