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:


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


2 Answers 2


How about

ClearAll[x, f]
h = {1, x, x^2 + 1, 3*x^3 + 2*x, 4*x^2 + 2*x}

And now

Mathematica graphics

I am sure there are other ways to do this.

  • $\begingroup$ Why are you restricting var to be a symbol? $\endgroup$
    – Roman
    Commented May 13, 2021 at 15:29
  • $\begingroup$ @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. $\endgroup$
    – Nasser
    Commented 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[[1]], x_] = #1) &, H];

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

(*    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     *)
  • $\begingroup$ 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? $\endgroup$
    – abka
    Commented May 13, 2021 at 15:43
  • $\begingroup$ Slots refer to the arguments of a pure function. In this case, the pure function (f[#2[[1]], x_] = #1) & sets the value of the function f with given arguments, which afterwards we can check with ?f as shown. $\endgroup$
    – Roman
    Commented May 13, 2021 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.