# How to define function that returns another function?

I'm new to Mathematica and I have an issue:

I'm trying to define a function that accepts as parameter another function with parameter X and then returns a function also with parameter X.

Input:

transform[x_[y_]] := {y, x[y]}

explicitFunction[x_] := Cos[π*x]/x

explicitFunction[ab]

parametric[x_] := transform[explicitFunction[x]]

parametric[ab]

expectedResult[x_] := {x, Cos[π*x]/x};

expectedResult[ab]


Output:

1. Cos[ab π]/ab
2. transform[Cos[ab π]/ab]
3. {ab, Cos[ab π]/ab}

Output no. 1: How a call to the explicit function which will also be a parameter looks like.

Output no. 2: How a call to the transform function with the explicit function as parameter looks like on my computer.

Output no. 3: What I actually want to achieve.

Obviously I can write expectedResult[x_] := {x, explicitFunction[x]}; but that's not the point. What I need is to be able to use a function expression/call with a function parameter and use the result later as if it's another function.

• use SetAttributes[transform, HoldFirst]
– kglr
Apr 25, 2023 at 9:10

Use Trace to see the source of the problem. Namely, explicitFunction[ab] is evaluated to Cos[ab π]/ab before transform is called; and, since Cos[ab π]/ab does not match the required argument pattern transform is returned unevaluated:

Trace @ parametric[ab] // Column


A fix: Give transform the attribute HoldFirst to prevent evaluation of its argument:

ClearAll[transform, explicitFunction, parametric, x, y]

SetAttributes[transform, HoldFirst]

transform[x_[y_]] := {y, x[y]}

explicitFunction[x_] := Cos[π*x]/x

parametric[x_] := transform[explicitFunction[x]]

parametric[ab]

 {ab, Cos[ab π]/ab}