Re: Letting functions not evaluate
- To: mathgroup at smc.vnet.net
- Subject: [mg79441] Re: Letting functions not evaluate
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Fri, 27 Jul 2007 05:42:15 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <f89qmn$60t$1@smc.vnet.net>
Josh Burkart wrote:
> Say I have a function f[x], and, for certain values of the argument x, I don't want it to evaluate to anything. E.g., say
>
> f[x_]:=Mod[10,x],
>
> and if x is not an integer, then I want f[x] to yield simply f[x]. One way to achieve this is through pattern matching, i.e.,
>
> f[x_Integer]:=Mod[10,x]
>
> Although this works perfectly in this example, it is somewhat limited. For instance, if I have a function taking two arguments and I want to perform some check on both arguments together to see whether the function should evaluate or not, pattern matching won't work. E.g.,
>
> g[x_,y_]:=Mod[10,x*y]
>
> only if x*y is an integer (even if x and y individually aren't integers). I think there's some way to do this more generally than pattern matching, since for instance if I enter
>
> In[11]:= Integrate[Gamma[x]^5,x]//FullForm
> Out[11]//FullForm= Integrate[Power[Gamma[x],5],x]
>
> Mathematica just returns the input unevaluated after taking a little time to decide it's not resolvable. Anyone know how to do this? Using an If[] statement doesn't work, since
>
> In[1]:= f[x_]:=If[IntegerQ[x], Mod[10, x], f[x]]
> In[4]:= f[3]
> Out[4]= 1
> In[3]:= f[3.3]
> During evaluation of In[3]:= $IterationLimit::itlim: Iteration limit of 4096 exceeded. >>
> Out[3]= Hold[f[3.3]]
>
> results in infinite recursion. HoldForm[] and Defer[] also produce somewhat dissatisfactory results, since the FullForm[] of what they return is actually HoldForm/Defer[blah blah].
Hi Josh,
You can had a test after the function declaration, as in
In[1]:= Clear[f]
f[x_] /; IntegerQ[x] := Mod[10, x]
{f[3], f[3.3]}
Out[3]= {1, f[3.3]}
or after the function definition,
In[4]:= Clear[f]
f[x_] := Mod[10, x] /; IntegerQ[x]
{f[3], f[3.3]}
Out[6]= {1, f[3.3]}
Therefore, for the function g we could write
In[7]:= Clear[g]
g[x_, y_] := Mod[10, x*y] /; IntegerQ[Rationalize[x*y]]
{g[3, 3], g[3, 3.3], g[3, 3.], g[2, 3.5], g[2, 7/2]}
Out[9]= {1, g[3, 3.3], 1., 3., 3}
Note that I have added a call to *Rationalize* because of the switch of
arithmetic models that occurs if you mixed Integer like 2 and Real like 2.0.
Regards,
Jean-Marc