# Define a function of a function of an arbitrary variable

I want to define a function called int that takes another function as an argument and yields an integral of that function from 0 to 1 (just for example).

So I tried:

int[f_]:= NIntegrate[f[x],{x,0,1}]


This now works like this:

int[Cos]
0.841471


or

int[Sin]
0.459698


However, if I want a specific function, like x Sin[E^x], I need to write this:

int[# Sin[Exp[#]]&]
0.411229


How do I define the function int so that it will work like

int[x Sin[Exp[x]]


or

int[t Sin[Exp[t]]


with any letter as an argument and yield the result?

I tried also this:

int[f_[x_]] := NIntegrate[f[x], {x, 0, 1}]


While int[Sin[t]] yields the correct result, int[t Sin[t]] just returns int[t Sin[t]].

• If you consider the syntax of Plot, Table, Integrate, etc., the variable is specified when the argument is an algebraic expression and not literally a function. E.g. a syntax of the form int[t Sin[t], t] identifies the variable (in the 2nd argument). – Michael E2 Jun 13 '18 at 22:05

int[f_] := With[{var = ReduceFreeVariables[f][]},
NIntegrate[f, {var, 0, 1}]]


so that

int[x Sin[Exp[x]]]


0.411229

but also

int[t Sin[Exp[t]]]


0.411229

And for example:

int[Cos@Cos@Cos@zzz]


0.786287

• Both of your answers are very nice, but I like this one more (I've never heard of FreeVariables)... – user16320 Jun 13 '18 at 22:46
• This is pretty cool; can you talk a little about what ReduceFreeVariables[f]does? I'm having trouble finding a description of FreeVariables in the help files. – Rudy Potter Jun 14 '18 at 0:05
• If you went to the linked answer, you'd see it's an undocumented function. Btw, for a bunch of undocumented functions see What are some useful, undocumented Mathematica functions? – corey979 Jun 14 '18 at 7:19

Try leaving the "[x]" out of the definition.

int[f_] := NIntegrate[f, {x, 0, 1}];
int[x Sin[Exp[x]]]
0.411229


If you need to be able to change the variable, you could do:

int2[fun_, var_] := NIntegrate[fun, {var, 0, 1}]
int2[x Sin[Exp[x]], x]
0.411229
`