Re: Determine if a parameter is a function
- To: mathgroup at smc.vnet.net
- Subject: [mg101746] Re: Determine if a parameter is a function
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Thu, 16 Jul 2009 08:16:51 -0400 (EDT)
- References: <h3kddu$g35$1@smc.vnet.net>
Hi, > 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. it might not be possible to really check that what you get is o.k. for what you do, but you could at least check whether a DownValue that matches one argument is defined. The correct number of arguments could be checked like this: MemberQ[ Cases[ DownValues[f], Verbatim[RuleDelayed][_[args_], _] :> Length[Unevaluated[args]] ], 1] The above will only work for user defined functions, the internal functions (most, but I think not all are in the Context "System`") usually have empty DownValues, although they behave as they would have DownValues defined. For these you could try to analyze the SyntaxInformation, e.g. like this: Length[DeleteCases[ "ArgumentsPattern" /. SyntaxInformation[Log], _Optional]] == 1 but there might be internal functions that are missing SyntaxInformation, so this might not be 100% robust. Depending on what you do there might be better approaches to catch invalid input. E.g. it is often possible to just try what you want and Catch error messages so the function aborts when the argument you assume to be a function doesn't behave well. hth, albert