Re: Argument typing in Compile
- To: mathgroup at smc.vnet.net
- Subject: [mg9412] Re: Argument typing in Compile
- From: Paul Abbott <paul at physics.uwa.edu.au>
- Date: Wed, 5 Nov 1997 01:56:30 -0500
- Organization: University of Western Australia
- Sender: owner-wri-mathgroup at wolfram.com
Sean Ross wrote:
> With normal mathematica functions, there is a built-in "case" structure
> for overloading the definition of a particular symbol. For example:
>
> f[x_Integer]:=function1;
> f[x_Real]:=function2;
This is fine:
In[1]:= f[x_Real] := f1[x]
In[2]:= f[x_Integer] := f2[x]
> Now suppose I want to do the same with CompiledFunction objects.
>
> f[x_Real]=Compile[{x,_Real},x^2] and other permutations where the
> symbol f is given an argument list generate an error message that
> Compile is protected.
This does not make sense because Compile[{x,_Real},x^2] is, essentially,
a pure function, i.e., x is a dummy variable. Also, to "type"
variables you need nested list brackets:
In[3]:= ?Compile
"Compile[{x1, x2, ... }, expr] creates a compiled function which
evaluates \
expr assuming numerical values of the xi. Compile[{{x1, t1}, ... },
expr] \
assumes that xi is of a type which matches ti. Compile[{{x1, t1, n1},
... }, \
expr] assumes that xi is a rank ni array of objects each of a type which
\
matches ti. Compile[vars, expr, {{p1, pt1}, ... }] assumes that \
subexpressions in expr which match pi are of types which match pti."
> Does anyone know of a way to define a symbol that will execute one bit
> of compiled code for certain types of arguments and another bit of
> compiled code for other arguments without resorting to an explicit If
> or Case structure?
With the definitions above, the following does what you want:
In[4]:= f1 = Compile[{{x, _Real}}, x^2];
In[5]:= f2 = Compile[{{x, _Integer}}, x^2];
In[6]:= f /@ {1, 2, 3, 4, 1., 2., 3., 4.}
Out[6]= {1,4,9,16,1.,4.,9.,16.}
Cheers,
Paul
____________________________________________________________________
Paul Abbott Phone: +61-8-9380-2734
Department of Physics Fax: +61-8-9380-1014
The University of Western Australia Nedlands WA 6907
mailto:paul at physics.uwa.edu.au AUSTRALIA
http://www.pd.uwa.edu.au/~paul
God IS a weakly left-handed dice player
____________________________________________________________________