[Date Index]
[Thread Index]
[Author Index]
Re: Checking function syntax
*To*: mathgroup at smc.vnet.net
*Subject*: [mg64605] Re: Checking function syntax
*From*: Paul Abbott <paul at physics.uwa.edu.au>
*Date*: Thu, 23 Feb 2006 00:35:54 -0500 (EST)
*Organization*: The University of Western Australia
*References*: <dthh6f$nai$1@smc.vnet.net>
*Sender*: owner-wri-mathgroup at wolfram.com
In article <dthh6f$nai$1 at smc.vnet.net>,
Chris Rodgers <rodgers at physchem.NOSPAMox.aREMOVEc.uk> wrote:
> How can I make my own functions give an error if they are called with
> the wrong syntax?
This is a FAQ -- but not so easy to find (a search on argx is a good way
to find the answer).
> For example, if I define this function
>
> In[37]:=
> MyFunc1[x_,y_]:=Tuples[{x,y},2]
>
> and then Map MyFunc2 over the result
>
> In[38]:=
> Map[MyFunc2,MyFunc1[a,b]]
>
> I get this (correct, desired) output.
>
> Out[38]=
> {MyFunc2[{a,a}],MyFunc2[{a,b}],MyFunc2[{b,a}],MyFunc2[{b,b}]}
>
> However, if I inadvertently added a third argument
>
> In[39]:=
> Map[MyFunc2,MyFunc1[a,b,c]]
>
> then I get this (correct, but undesired) output
>
> Out[39]=
> MyFunc1[MyFunc2[a],MyFunc2[b],MyFunc2[c]]
>
> I would prefer to get some sort of error message in the second case,
> such as the built-in function Sin[...] produces when called with the
> wrong number of arguments.
>
> In[41]:=
> Sin[1.]
> Out[41]=
> 0.841471
> In[42]:=
> Sin[2,3]
> From In[42]:=
> Sin::argx : Sin called with 2 arguments; 1 argument is expected. Out[42]=
> Sin[2,3]
The following rule issues an error message (using the built-in Message
mechanism via "argrx" -- look this up in the Help Browser) if f is
called with an incorrect number (e.g. != 2) of arguments:
f[args___]:= Null/; Length[{args}] != 2 &&
Message[f::"argrx", f, Length[{args}], 2]
As a side-effect of evaluating the Condition the rule on the right-hand
side computes the number of arguments using Length and prints a message
when it is not equal to two.
f[1,2,3]
f::"argrx": f called with 3 arguments; 2 arguments are expected. More...
f[1, 2, 3]
Cheers,
Paul
_______________________________________________________________________
Paul Abbott Phone: 61 8 6488 2734
School of Physics, M013 Fax: +61 8 6488 1014
The University of Western Australia (CRICOS Provider No 00126G)
AUSTRALIA http://physics.uwa.edu.au/~paul
Prev by Date:
**Re: General--Making the DisplayFormula style in ArticleModern look like Traditional**
Next by Date:
**Re: Not Using a Text Editor Interface for Mathematica**
Previous by thread:
**Re: Checking function syntax**
Next by thread:
**Re: Checking function syntax**
| |