2
$\begingroup$

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.

$\endgroup$
1
  • 2
    $\begingroup$ use SetAttributes[transform, HoldFirst] $\endgroup$
    – kglr
    Apr 25, 2023 at 9:10

1 Answer 1

4
$\begingroup$

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

enter image description here

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}
$\endgroup$

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.