Re: Not accepting function as parameter
- To: mathgroup at smc.vnet.net
- Subject: [mg71697] Re: Not accepting function as parameter
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Mon, 27 Nov 2006 04:03:59 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <ekbmj4$f87$1@smc.vnet.net>
wooks wrote:
> This is a piece of experimental code. The function happy does not
> evaluate whenever I pass f as a parameter as in the example below.
>
> Clear[happy]
> happy[ f_Function, a_Integer, b_Integer] := Module[{width = (b -
> a)/1000},
> f[width]];
>
> happy[ Sin, 1, 21]
>
> I'd be grateful for help.
>
The issue is that built-in mathematical functions such as Sin, Cos, Log,
etc, have _Symbol_ for head and not _Function_. On the other hand, pure
function have _Function_ for head. You can test the head of any
Mathematica expression with /Head/ (See below for an example.)
Therefore, you must add an alternative condition to the pattern f to
take in account both possibilities.
In[1]:=
Head[Sin]
Out[1]=
Symbol
In[2]:=
Head[#1^2 & ]
Out[2]=
Function
In[3]:=
Clear[happy]
happy[(f_Symbol) | (f_Function), a_Integer,
b_Integer] := Module[{width = (b - a)/1000},
f[width]];
happy[Sin, 1, 21]
happy[#1^2 & , 1, 21]
happy[N[#1^2] & , 1, 21]
Out[5]=
Sin[1/50]
Out[6]=
1/2500
Out[7]=
0.0004
HTH,
Jean-Marc