# Help with defining a function

Posted 9 years ago
5357 Views
|
4 Replies
|
5 Total Likes
|
 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
4 Replies
Sort By:
Posted 9 years ago
 In[16]:= MyInt[f_[x_]] := Integrate[f[x], x]  In[17]:= f[x] := x^3;  In[18]:= MyInt[f[x]] // Trace  Out[18]= {{\!$$\* TagBox[ RowBox[{"f", "[", "x", "]"}],HoldForm]$$, \!$$\*TagBox[SuperscriptBox["x", "3"],HoldForm]$$}, \!$$\*TagBox[RowBox[{"MyInt", "[", SuperscriptBox["x", "3"], "]"}],HoldForm]$$}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 9 years ago
 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 9 years ago
 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]= {}Thanks
Posted 9 years ago
 In[33]:= MyInt[f_] := Integrate[f[x], x]In[34]:= MyInt[#^3 &]Out[34]= x^4/4
Community posts can be styled and formatted using the Markdown syntax.