MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Determine if a parameter is a function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg101778] Re: Determine if a parameter is a function
  • From: Valeri Astanoff <astanoff at gmail.com>
  • Date: Fri, 17 Jul 2009 05:01:16 -0400 (EDT)
  • References: <h3kddu$g35$1@smc.vnet.net>

On 15 juil, 13:09, Peter Breitfeld <ph... at t-online.de> wrote:
> Suppose I have a function eg
>
> myfunc[f_,x_]:= <some definitions>
>
> f should be a pure function like (#^2&) or Function[{x},x^2] or a named
> function either self defined, like
>
> f[x_]:=x^2   or g[x_]=x^2
>
> or built-in like Sin, Log, ...
>
> How can I test if f is any of these, to be able to yield a message on
> wrong input?
>
> I found that the pure-functions have Head Function, but all the others
> have Head Symbol, so asking for the head is not sufficient.
>
> --
> _________________________________________________________________
> Peter Breitfeld, Bad Saulgau, Germany --http://www.pBreitfeld.de


Good day,

This way to do it should be ok for almost all non-pathological cases :

In[1]:= myfunc::nfun="argument `1` should be a function.";

In[2]:= myfunc[(f_?NumericQ|f_List|f:(True|False)),x_]:=
(Message[myfunc::nfun,f]; HoldForm@myfunc[f,x]);

myfunc[f_Symbol /; DownValues[f]=={} && Attributes[f]=={},x_]:=
(Message[myfunc::nfun,f]; HoldForm@myfunc[f,x]);

myfunc[f_,x_]=f[x];


A few tests :

In[5]:= f1=#^2&;

In[6]:= f2[x_]=x^2;

In[7]:= f3=Function[{x},x^2];

In[8]:= myfunc[f1,x]
Out[8]= x^2

In[9]:= myfunc[f2,x]
Out[9]= x^2

In[10]:= myfunc[f3,x]
Out[10]= x^2

In[11]:= myfunc[ff,x]
 myfunc::nfun: argument ff should be a function.
Out[11]= myfunc[ff,x]

In[12]:= myfunc[1,x]
 myfunc::nfun: argument 1 should be a function.
Out[12]= myfunc[1,x]

In[13]:= myfunc[{1,2},x]
 myfunc::nfun: argument {1,2} should be a function.
Out[13]= myfunc[{1,2},x]

In[14]:= myfunc[True,x]
 myfunc::nfun: argument True should be a function.
Out[14]= myfunc[True,x]

In[15]:= myfunc[Sin,x]
Out[15]= Sin[x]

--
V.Astanoff


  • Prev by Date: Re: Bug, quirk or expected behavior of Slot[]?
  • Next by Date: Re: False divergence of the NDSolve solution: how to avoid
  • Previous by thread: Re: Determine if a parameter is a function
  • Next by thread: Re: Determine if a parameter is a function