Message Boards Message Boards

4 Replies
5 Total Likes
View groups...
Share this post:

Help with defining a function

Here is a simple example of the problem I cannot solve.
In[4]:= MyInt[f_[x_]] := Integrate[f[x], x]

In[6]:= f[x] := x^3;

In[7]:= MyInt[f[x]]
Out[7]= MyInt[x^3]

If anyone can tell my why I do not get the integration to work I would be most grateful.

Many thanks,
Dick Fell
POSTED BY: richard fell
4 Replies
 In[16]:= MyInt[f_[x_]] := Integrate[f[x], x]
 In[17]:= f[x] := x^3;
 In[18]:= MyInt[f[x]] // Trace
 Out[18]= {{\!\(\*
 RowBox[{"f", "[", "x", "]"}],
HoldForm]\), \!\(\*
SuperscriptBox["x", "3"],
HoldForm]\)}, \!\(\*
RowBox[{"MyInt", "[",
SuperscriptBox["x", "3"], "]"}],
Shows that f was replaced by x^3 in the first step, so MyInt[x^3] didn't pattern match to the definition of MyInt
POSTED BY: Frank Kampas
The issue is with the order in which things will evaluate. You can use Trace to see the order that things will evaluate in.

I don't reccomend programming this way if avoidable. Changing the order of evaluation for things can quickly make code difficult to read.

What you want to do is prevent the argument to MyInt from evaluating before it is used. Functions which do this have the attribute "HoldFirst" or "HoldAll"
SetAttributes[MyInt, HoldAll]
MyInt[f_[x_]] := Integrate[f[x], x];
f[x] := x^3;
POSTED BY: Sean Clarke
Thank you both for your answers.

If you do not mind, would you comment on why thisĀ  does not work? Clearly, I am still confused about Mathematica's evaluation process.

In[8]:= SetAttributes[MyResidue, HoldAll]
In[9]:= MyResidue[f_[p0_], pole] := Residue[f[p0], {p0, pole}]

In[10]:= f[p0_] := 1/(p0^2 - (wp - I*e1)^2)

In[11]:= MyResidue[f[p0], -wp + I*e1]

Out[11]= MyResidue[f[p0], -wp + I e1]

In[12]:= Trace[MyResidue[f[p0], -wp + I*e1]]

Out[12]= {}

POSTED BY: richard fell
In[33]:= MyInt[f_] := Integrate[f[x], x]

In[34]:= MyInt[#^3 &]

Out[34]= x^4/4
POSTED BY: Frank Kampas
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract