Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #15831

Re: Mixing optional parameters and options

From "Sjoerd C. de Vries" <sjoerd.c.devries@gmail.com>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Mixing optional parameters and options
Date 2011-02-04 06:44 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <iig781$rlo$1@smc.vnet.net> (permalink)
References <iie0bv$bt3$1@smc.vnet.net>

Show all headers | View raw


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

Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Mixing optional parameters and options "Sjoerd C. de Vries" <sjoerd.c.devries@gmail.com> - 2011-02-04 06:44 +0000

csiph-web