MathGroup Archive 1995

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

Search the Archive

Re: Options in self-defined functions

  • To: mathgroup at
  • Subject: [mg1674] Re: [mg1612] Options in self-defined functions
  • From: Anthony Rebello <arebello at>
  • Date: Tue, 11 Jul 1995 05:47:20 -0400

	Meader's book on Programming in Mathematica offers a very 
informative discussion on defining options, here is the gist of it.  
Lets say we are defining a function f which takes one argument and we 
want it to have an option called Opt.  We first define the default taking 
into consideration that we may want to add more options later.

Options[f] = {Opt->defaultval};

Next we define the function with a line to extract the default value from 
Options[f] or to take a user defined value if they input one, and finally 
include some expression involving the value of Opt and the argument of 
our function which was the reason we wanted to define a function in the 
first place.

f[x_,opts___Rule] := 
	opt = Opt /. {opts} /. Options[f];
	expression involving opt and x

Note that the triple underscore pattern object opts___Rule is neccessarry 
because we want to allow the user to give no option setting if they so 
choose, and of course we only want to allow options of the form lhs -> rhs 
after the first argument.  Here is a more concrete example, power[x] squaring 
x by default but allowing us to change exponent if we want to.

Options[power] = {exponent->2};

power[x_,opts___Rule] := 
	exp = exponent /. {opts} /. Options[power];

.                                         R              
L                                         E               
I             Anthony Rebello             |       
V              Knox  College              T                           
E             Math Department             H                 
|                                         E              
L                                         |      

  • Prev by Date: Re: Re: Crossreference, code documentation
  • Next by Date: Q: Mathematica & minimal surfaces
  • Previous by thread: Re: Options in self-defined functions
  • Next by thread: Re: Options in self-defined functions