Re: Mixing optional parameters and options

• To: mathgroup at smc.vnet.net
• Subject: [mg116193] Re: Mixing optional parameters and options
• From: "Sjoerd C. de Vries" <sjoerd.c.devries at gmail.com>
• Date: Fri, 4 Feb 2011 01:42:06 -0500 (EST)
• References: <iie0bv\$bt3\$1@smc.vnet.net>

```Hi Peter,

I'd say this is the expected result. Since a rule itself makes a
perfectly legal argument for a function, how could a function be able
to differentiate between a function call with two arguments (a
'standard' one and a rule) and a function call with 1 explicit
parameter, 1 implicit one and an option? Therefore, the only valid
interpretation in situations with optional parameters is to match
strictly from left to right.

An exception would be the case where additional heads take care of
disambiguation as in:

In[29]:= g[x_: 1, y_String: "qwerty", z_: 2] := {x, y, z}

In[30]:= g[]

Out[30]= {1, "qwerty", 2}

In[32]:= g[1, 2]

Out[32]= {1, "qwerty", 2}

In your case adding /; NumericQ[y] at the end of the definition would
seem to do the magic trick:

ClearAll[f]
Options[f] = {bla -> True};
f[x_, y_: 11, OptionsPattern[]] :=  If[OptionValue[bla], x*y, y/x] /;
NumericQ[y]

In[138]:= f[5, 7, bla -> False]
f[5, bla -> False]
f[5, 7]
f[5]

Out[138]= 7/5

Out[139]= 11/5

Out[140]= 35

Out[141]= 55

Cheers -- Sjoerd

On Feb 3, 11:34 am, Peter Breitfeld <ph... at t-online.de> wrote:
> To give a simpe example which, I hope, makes clear my issue:
> Suppose I define this (silly) example function:
>
> Options[f]={bla->True};
> f[x_,y_:11,OptionsPattern[]:=If[OptionValue[bla],x*y,y/x]
>
> Now:
> f[5]    ----> 55 (ok)
> f[5,7]  ----> 35 (ok)
>
> f[5,7,bla->False]  ----> 7/5 (ok)
> f[5,bla->False]    ----> 5*(bla->False)
>
> I expected the result 11/5
>
> The only way I found was to define f like this:
>
> f[{x_,y_:11},OptionsPattern[]]
>
> Can it be done without the curly braces?
>
> Thank you
> --
> _________________________________________________________________
> Peter Breitfeld, Bad Saulgau, Germany --http://www.pBreitfeld.de

```

• Prev by Date: Re: Eliminate
• Next by Date: Re: Anyone know of a book on Mathematica suitable for 16-18year old?
• Previous by thread: Re: Mixing optional parameters and options
• Next by thread: Re: Remove Symbolize