# Converting a vector of expressions into functions with the index being an input

I am trying to generate a list of functions from a vector of expressions. I have the list

$$H=[1,x,x^2+1,3x^3+2x,4x^2+2x]$$ and I want to define a function $$f$$ using two inputs such that $$f(n,x)$$ returns the evaluation of the $$n$$th entry of $$H$$. For example, I want $$f(3,y)=y^2+1$$.

I tried this:

test[n_,y_]:=Module[
{func},
func[x_]:=Evaluate[Part[H,n]];
func[y]
].


However, it always return an expression of $$x$$ instead of the function output. Can anyone please help me?

ClearAll[x, f]
h = {1, x, x^2 + 1, 3*x^3 + 2*x, 4*x^2 + 2*x}
f[(n_Integer)?Positive,var_Symbol]:=(h[[n]]/.x->var)


And now I am sure there are other ways to do this.

• Why are you restricting var to be a symbol? May 13, 2021 at 15:29
• @Roman well, from the spirit of the intended use, the var parameter is expected to be a symbol. But ofcourse one can change or remove this if that is not what they wanted. May 13, 2021 at 17:54
H = {1, x, x^2 + 1, 3*x^3 + 2*x, 4*x^2 + 2*x};
MapIndexed[(f[#2[], x_] = #1) &, H];

f[3, y]
(*    1 + y^2    *)

?f
(*    f[1, x_] = 1
f[2, x_] = x
f[3, x_] = 1 + x^2
f[4, x_] = 2 x + 3 x^3
f[5, x_] = 2 x + 4 x^2     *)

• Thank you very much. I am a bit new to the language so can you plese explain to me the meaning of the second line of your code? What does the & do and what are #2 and #1?
– abka
May 13, 2021 at 15:43
• Slots refer to the arguments of a pure function. In this case, the pure function (f[#2[], x_] = #1) & sets the value of the function f with given arguments, which afterwards we can check with ?f as shown. May 13, 2021 at 16:49