Re: Programming with options.
- To: mathgroup at smc.vnet.net
- Subject: [mg68088] Re: Programming with options.
- From: Bill Rowe <readnewsciv at earthlink.net>
- Date: Sat, 22 Jul 2006 06:24:11 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
On 7/21/06 at 5:37 AM, maxart.yZEROSPAM at tiscali.it (MaxArt) wrote: >I want to create some new functions in Mathematica (4.0), and I >want it to work with options like Plot and other graphic functions. >The idea behind this is to modify the result and the behaviour of my >functions when extra arguments are given, and I thought that the use >of options would be perfect. For example, if I want to create a >function Pow that gives the square of a number, except when an >option Exponent is given, so that Pow[a, Exponent -> 3] yields a^3. >How can I do that? Here is a simple example, First, I will define the default option In[24]:= Options[distance]={Method->Euclidean}; Next define the function In[25]:= distance[x_, y_, opts___] := Norm[{x, y}, Method /. {opts} /. Options[distance] /. { Euclidean->2, Absolute->1, Method->2] Here the triple blank represents a sequence of 0 or more parameters named opts Now, evaluating the function can be done as follows: In[26]:= distance[{1,2},{2,3}] Out[26]= Sqrt[9 + 4*Sqrt[5]] In[27]:= distance[{1,2},{2,3},Method->Absolute] Out[27]= 5 The replacement rules in the function definition are designed to first apply user specified rules. If these do not contain a replacement rule for Method, Options[distance] evaluates to the default option for distance. Next, the allowed options are replaced with values acceptable to Norm. The last rule Method->2 ensures Norm gets a valid value for the second argument when no default option for distance is defined. -- To reply via email subtract one hundred and four