MathGroup Archive 2006

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

Search the Archive

Re: Checking function syntax

  • To: mathgroup at smc.vnet.net
  • Subject: [mg64631] Re: Checking function syntax
  • From: Chris Rodgers <rodgers at physchem.NOSPAMox.aREMOVEc.uk>
  • Date: Fri, 24 Feb 2006 00:18:48 -0500 (EST)
  • Organization: Oxford University, England
  • References: <dthh6f$nai$1@smc.vnet.net> <dtjkmo$drv$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

> 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.

Thanks for this. I eventually came up with something similar to the 
other posters' ideas, but I like the fact that this idea (a) prints a 
warning message and (b) leaves the erroneous input unevaluated rather 
than returning e.g. False or Null.

For the benefit of the archives (and future users of Google), here is my 
attempt at using this idea. I define a function called NeedsArgs that 
may be called on a symbol (and optionally given the desired number of 
arguments). It adds an appropriate rule to that symbol for error 
checking. I illustrate usage by calling NeedsArgs on itself.

(* Define a utility function to perform syntax-checking on our other 
definitions *)
NeedsArgs[sym_Symbol] := (
     sym::argcount = "`1` called with `2` arguments: this is not correct.";
     AppendTo[DownValues[sym],HoldPattern[sym[a___]] :> Null /; 
Message[sym::argcount, sym, Length[{a}]]];);

NeedsArgs[sym_Symbol,argc_Integer] := (
     sym::argcount = "`1` called with `2` arguments: " <> ToString[argc] 
<> " argument(s) are required.";
     AppendTo[DownValues[sym],HoldPattern[sym[a___]] :> Null /; 
Length[{a}] != argc && Message[sym::argcount, sym, Length[{a}]]];);

NeedsArgs[NeedsArgs];

(* Notice that this is OK *)
NeedsArgs[f];

(* But that this fails gracefully *)
NeedsArgs[f,g,h];

Thanks to everyone who helped,

Chris.


  • Prev by Date: GeometricalGeodesy for Mathematica Now Available
  • Next by Date: Re: Re: finding the position of a pattern in list (Correction)
  • Previous by thread: Re: Checking function syntax
  • Next by thread: Surface graphing question