MathGroup Archive 2008

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

Search the Archive

Re: Help with Check Function Arguments & Options

  • To: mathgroup at smc.vnet.net
  • Subject: [mg87278] Re: Help with Check Function Arguments & Options
  • From: Albert Retey <awnl at arcor.net>
  • Date: Sun, 6 Apr 2008 06:43:57 -0400 (EDT)
  • References: <ft7gkq$bve$1@smc.vnet.net>

Andrew Beveridge wrote:
> I would like to thank everyone who has previously responded to my 
> posts. Your advice has helped greatly.
> 
> I have a couple of final questions.
> 
> I am writing a package file and would like to do some argument and 
> option checking if possible; that is check the number of arguments 
> and see if there are unknown options.
> 
> If my function has no options I think I can do this.
> 
> f[x_,y_] := x + y
> f[args___] := If[Length[{args}] != 2, Message[f::"argrx", f, 
> Length[{args}], 2]; Return[$Failed]]
> 
> This type of check has been posted to the message board before.
> 
> My question is assume that f[x,y] has multiple options, that is
> Options[f] = {opt1 -> 1, opt2 -> True}, etc
> 
> How do I check if the user entered the correct options?

I think this is what you would usually do (this is for version 6, 
OptionPattern did not exist in older versions, where you could instead 
use the pattern  ___?OptionQ):

Options[f]={opt1->1,opt2->2};
f::argx="`1`";
f[x_,y_,OptionsPattern[f]]:=x+y
f[args___]:=(Message[f::argx,ToString@{args}];$Failed)

Note that patterns are automagically sorted so that more special 
patterns will be tried before more general ones. So there is no need to 
check for the number of arguments in the last pattern, which will match 
everything but only will be tried when the first does not match.

the above definitions for f will behave as follows:

In[28]:= f[1,2]
Out[28]= 3
In[29]:= f[1,2,3]
During evaluation of In[29]:= f::argx: {1, 2, 3} >>
Out[29]= $Failed
In[30]:= f[1,2,opt1->3,opt2->4]
Out[30]= 3

But note that it does not complain about unknown options, these will 
just be ignored:

In[31]:= f[1,2,opt1->3,opt3->4]
Out[31]= 3


AFAIK, to check whether only known options were given would need extra 
code in the definition of f's body or more complicated patterns for the 
definition.

hth,

albert


  • Prev by Date: Re: How to put text on a curved surface?
  • Next by Date: Re: Re: Label vertices in Graph to display with GraphPlot
  • Previous by thread: Re: Help with Check Function Arguments & Options
  • Next by thread: Re: Help with Check Function Arguments & Options