List of functions

fun = {x^2 + 1, x + 5, x^3};

I don't think you really want to define f as

f[x_]:=fun[[1]]

If you look at the Global symbol f after making this definition it shows up as:

?f

Mathematica graphics

It works but there are two caveats:

  1. You get the expected answer only as long as fun remains unchanged.

  2. Each time you run it there is an extra evaluations step (i.e., fun[[1]] gets replaced with 1 + x^5) and then that is evaluated.

Below is a Trace of f[x].

Mathematica graphics

I think it is more productive to define f as

f[x_] := Evaluate[fun[[1]]]

Now when we look at the Global symbol f one sees:

Mathematica graphics

After the definition is made f is no longer dependent on fun.

Further it requires fewer evaluation steps.

Mathematica graphics


ClearAl[[f]
f[x_] := fun[[1]]

{f[u], f[5]}

{ 1 + u^2, 26}

You can also define three pure functions from fun:

ClearAll[f1, f2, f3]
{f1, f2, f3} = Function[x, #] & /@ fun;

{f1[t], f1[5]}

{ 1 + t^2, 26}

Alternatively,

ClearAll[g1, g2, g3]
{g1[x_], g2[x_], g3[x_]} := Evaluate @ fun;

{g1[y], g2[q], g3[s], g1[5], g2[5], g3[5]}

{1 + y^2, 5 + q, s^3, 26, 10, 125}


This is an example where you shd use Set rather than SetDelayed.

ClearAll[f, x]
fun = {x^2 + 1, x + 5, x^3};
f[x_] := fun[[1]]
DownValues[f]  (* {HoldPattern[f[x_]] :> fun[[1]]} *)
ClearAll[f, x]
fun = {x^2 + 1, x + 5, x^3};
f[x_] = fun[[1]]
DownValues[f]   (* {HoldPattern[f[x_]] :> 1 + x^2} *)

Tags:

Functions