MathGroup Archive 2009

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

Search the Archive

Functions with variable number of arguments and options

  • To: mathgroup at smc.vnet.net
  • Subject: [mg105884] Functions with variable number of arguments and options
  • From: Thomas Münch <thomas.muench at gmail.com>
  • Date: Wed, 23 Dec 2009 02:41:42 -0500 (EST)

Dear Mathgroup,

I can't figure out how to define a function properly that has a variable 
number of arguments and options. When I call the function with less than 
the full set of arguments, I want the missing arguments to take on 
default values. Below are two toy examples, functions f and g, that both 
behave identical. How do I make the options work when I call the 
function with less than the full set of arguments?

Thank you for your help,

thomas


Clear[f];
Options[f]={opt->"DefaultOptionValue"};
SyntaxInformation[f]={"ArgumentsPattern"->{{_,_.,_.},OptionsPattern[]}};
f[x_,y_,z_,OptionsPattern[]]:={"f",x,y,z,OptionValue[opt]}
f[x_,y_,OptionsPattern[]]:={"f",x,y,0,OptionValue[opt]}
f[x_,OptionsPattern[]]:={"f",x,0,0,OptionValue[opt]}

Clear[g];
Options[g]={opt->"DefaultOptionValue"};
SyntaxInformation[g]={"ArgumentsPattern"->{{_,_.,_.},OptionsPattern[]}};
g[x_,y_:0,z_:0,OptionsPattern[]]:={"g",x,y,z,OptionValue[opt]}

(* The following simple function calls work as expected, both for f and 
for g *)

f[1]
f[2,2]
f[3,3,3]

g[1]
g[2,2]
g[3,3,3]

(* But if one wants to specify a different value for the option, it only 
works if the full number of arguments are supplied, in this case 3 
arguments. Otherwise, the option is interpreted as the second or third 
argument instead of an option: *)

f[1,opt->"SpecialValue"]
f[2,2,opt->"SpecialValue"]
f[3,3,3,opt->"SpecialValue"] (*only this works*)

g[1,opt->"SpecialValue"]
g[2,2,opt->"SpecialValue"]
g[3,3,3,opt->"SpecialValue"] (*only this works*)




  • Prev by Date: Re: Twitter.m (Twittering With Mathematica) broken?
  • Next by Date: Re: Toolbar
  • Previous by thread: Re: Re: NDSolve: Wrong Diagnosis as Delay Differential-Algebraic
  • Next by thread: Re: Functions with variable number of arguments and