# Using a loop to make a vector of functions

I am trying to use a do loop to make a vector of an arbitrary number of functions that can be evaluated later. I think the problem I am having is because of the AppendTo function in my code, because when I hard code a short vector it does what I want. For example:

Y[{x_}] = {x} + {3}
Y[{8}]
(*works, but*)
ClearAll[X]
X[{x_}] = {};
Do[AppendTo[X[{x}], x + 3], 1];
X[{8}]


does not. Does anyone have any tips or advice to make this work?

• Check X[{x}] to see what your Do[AppendTo[... is doing. To get what you seek, you would need to somehow include your Do[AppendTo[... inside the definition of X[{x_}], which isn't natural. Are you trying to do something else with this? If you tell us what that is, we can better help you. As written, your first method (though you should use SetDelayed rather than Set) appears to be the natural way to do it. – jjc385 Nov 12 '17 at 1:40
• Have you seen Function and its shorthand &? – Edmund Nov 12 '17 at 1:45
• If these functions are related (I assume they must be if there's an "arbitrary number" of them), you could try something like ft = Table[With[{k = k}, k - #^k &], {k, 3}]. It's hard to know what would be best without some idea of how you're going to use them. – aardvark2012 Nov 12 '17 at 11:28

## 2 Answers

The example you have provided does not align well with the language of the question.

If you would like to have a vector of functions, you can simply store all the function definitions in a list and define an application function, like so:

ClearAll[fnList1,applyFList];

fnList1 = {
# + 1 &,
2 * # + 3 &
};

applyFnList = With[{fnl = #1, a = #2}, Map[#[a] &, fnl]] &;

applyFnList[fnList1, 3]

(* Output = {4, 9} *)


Now you can append (or prepend) an element to the list of functions:

fnList2 = Append[fnList1, 3 * # - 4 &];


and still invoke the new list with applyFnList:

applyFnList[fnList2, 3]

(* Output = {4, 9, 5} *)


If, on the other hand, you meant something else, please clarify your question.

Modify DownValues[X]:

ClearAll[X]
X[{x_}] = {};

DownValues[X] = Replace[DownValues[X],
(Verbatim[HoldPattern[X[{x_}]]] :> {a___}) ->
Verbatim[HoldPattern[X[{x_}]]] :> {a, 3 + x}, {1}] /. Verbatim -> Identity
X[{8}]


{11}