MathGroup Archive 2010

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

Search the Archive

Re: Question on defaults in positional arguments

  • To: mathgroup at smc.vnet.net
  • Subject: [mg112625] Re: Question on defaults in positional arguments
  • From: Albert Retey <awnl at gmx-topmail.de>
  • Date: Thu, 23 Sep 2010 04:23:13 -0400 (EDT)
  • References: <i79hsa$ofd$1@smc.vnet.net>

Am 21.09.2010 08:03, schrieb NP:
> Hi,
> 
> I was wondering if there was a way in selectively specifying some of
> the arguments of a function (rest remaining default). For instance,
> consider
> Clear[f, x, y,z];
> f[x_: 1, y_: 2,z_:3] := {x, y}
> f[5]
> 
> {5,2,3}
> 
> Here the default values of y and z are automatically used. How can I
> call f so that, for example,  the default value of x  and z are used
> instead?

AFAIK there is no tricky pattern which would let you do that. I see to
common ways to solve your problem:

1) use options instead of positional arguments:

Options[f] = {x->1,y->2,z->3};
f[OptionsPattern[]]:={OptionValue[x],OptionValue[y],OptionValue[z]}

f[y->5]

2) use a placeholder like Automatic to mark the empty slots:

f[xx_:Automatic,yy_:Automatic,zz_:Automatic] := With[{
   x=Replace[xx,Automatic:>1],
   y=Replace[yy,Automatic:>2],
   z=Replace[zz,Automatic:>3]
},
{x,y,z}
]

f[Automatic,4]

If you extend the pattern to also replace Null you could even use an
empty argument, although the frontend will mark it as a syntax error and
I think it contradicts the usual design rules:

f[xx_: Automatic, yy_: Automatic, zz_: Automatic] := With[{
   x = Replace[xx, Automatic | Null :> 1],
   y = Replace[yy, Automatic | Null :> 2],
   z = Replace[zz, Automatic | Null :> 3]
   }, {x, y, z}]

f[,7]

hth,

albert


  • Prev by Date: Re: ImagePadding and PlotRange anomaly
  • Next by Date: Re: should Positive[ complexNumber ] return undefined instead of False?
  • Previous by thread: Re: Question on defaults in positional arguments
  • Next by thread: mathematica code for DWBA calculation