Re: Options in self-defined functions
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg1674] Re: [mg1612] Options in self-defined functions
- From: Anthony Rebello <arebello at knox.edu>
- 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] := Module[{opt}, 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] := Module[{exp}, exp = exponent /. {opts} /. Options[power]; x^exp ] NUMBERS-ARE-THE-ROOT-OF-ALL-EVIL..NUMBERS_A . R L E I Anthony Rebello | V Knox College T E Math Department H | E L | LA-FO-TOOR-EHT-ERA-SREBMUN.LIVE-LLA-FO-TOOR