Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2009

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

Search the Archive

Re: Why use OptionsPattern, OptionsValue ?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg102398] Re: Why use OptionsPattern, OptionsValue ?
  • From: David Bailey <dave at removedbailey.co.uk>
  • Date: Sat, 8 Aug 2009 04:36:45 -0400 (EDT)
  • References: <h58rgj$q8r$1@smc.vnet.net>

Ted Ersek wrote:
> Prior to Mathematica version 6 a good way to write a function with two
> options was the following.
> 
> -----------------------------------------------------------
> Options[foo] = {Opt1 -> val1, Opt2 -> val2};
> 
> foo[x_, opts___?OptionQ] := Module[{optn1, optn2},
>     {optn1, optn2} = {Opt1, Opt2} /. Flatten[{opts, Options[foo]}];
>     Blah[x, optn1, optn2]
> ]
> 
> ----------------------------------------------------------
> I am pretty sure the program above does the same thing in every version 
> of Mathematica (since version 3 if not earlier). However, as of 
> Mathematica 6 we have OptionsPattern, and OptionsValue. It seems the 
> main utility of OptionsPattern, and OptionsValue are to define functions 
> such as the one above.
> 
> One clear advantage to the old approach (see my example above) is that 
> you end up with code that works well across many versions of 
> Mathematica. What are the advantages to implementing options using 
> OptionsPattern, and OptionsValue?
> 
> Thanks,
>     Ted Ersek
> 
> 
> 
> 
One advantage/feature (depending on your point of view) is that the name 
of an option can be specified without regard to context, and can even be 
a string.

Another, is that using non-existent options generates an error message:

In[5]:= Options[foo] = {aaa -> 0};

foo[OptionsPattern[]] := OptionValue[aaa]

In[7]:= foo[aaa -> 9]

Out[7]= 9

In[8]:= foo["aaa" -> 8]

Out[8]= 8

In[9]:= foo[bbb -> 10]

During evaluation of In[9]:= OptionValue::nodef: Unknown option bbb for 
foo.

The built-in mechanism also handles options specified with Rule or 
RuleDelayed without complication.

I always use the new mechanism, but I don't write code for use with 
pre-version 6.

David Bailey
http://www.dbaileyconsultancy.co.uk


  • Prev by Date: Re: Re: error with Sum and Infinity
  • Next by Date: Re: Legends for Plot's (solution)
  • Previous by thread: Why use OptionsPattern, OptionsValue ?
  • Next by thread: Re: Multiplication of matrices