MathGroup Archive 2006

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

Search the Archive

Re: Checking function syntax

  • To: mathgroup at smc.vnet.net
  • Subject: [mg64572] Re: Checking function syntax
  • From: dh <dh at metrohm.ch>
  • Date: Thu, 23 Feb 2006 00:34:06 -0500 (EST)
  • References: <dthh6f$nai$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Hi Chris,
your problem can be solved by noting that special definitions are 
examined before more general ones.
Here is an example:

Remove[f];
f[a_, b_] := Print["Right number of arguments"];
f[___] := Print["Wrong number of arguments"];
f[1]
f[1, 2]
f[1, 2, 3]

Daniel

Chris Rodgers wrote:
> Hi,
> 
> How can I make my own functions give an error if they are called with 
> the wrong syntax?
> 
> 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]
> 
> Many thanks,
> 
> Chris.
> 


  • Prev by Date: Re: LeftClick+Shift+Enter Reassign
  • Next by Date: Re: Matrix multiplication problem fixed via dot operation.
  • Previous by thread: Re: Checking function syntax
  • Next by thread: Re: Checking function syntax