MathGroup Archive 2002

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

Search the Archive

cleaner way to do Options (named arguments)

  • To: mathgroup at smc.vnet.net
  • Subject: [mg33448] cleaner way to do Options (named arguments)
  • From: Daniel Reeves <dreeves at flip.eecs.umich.edu>
  • Date: Thu, 21 Mar 2002 09:27:47 -0500 (EST)
  • Organization: University of Michigan Engineering
  • Sender: owner-wri-mathgroup at wolfram.com

I found that creating a function with Options (named arguments) was clunky
so I wrote the following function:

SetAttributes[withOptions, HoldAll];
withOptions[defaults_, overrides_, body_] :=
  ReleaseHold[Hold[body]/.Evaluate[overrides]/.Evaluate[defaults]]

With that defined, creating a function with Options is a little cleaner.
For example:

Options[f] = {a -> 1, b -> 2};
f[x_, opts___] := withOptions[Options[f], {opts},
  (* body of f here... *)
  {x,a,b}
]

One problem with that is that 2 functions with the same options can't call
each other.  So maybe the following version is better:

SetAttributes[withOptions, HoldAll];
withOptions[defaults_, overrides_, body_]:=
  ReleaseHold[ Hold[body]
    /. (opt[#1]->#2&) @@@ Join[Evaluate[overrides],Evaluate[defaults]]]

and now the example would be defined as like so:

Options[f]= {a -> 1, b -> 2};
f[x_, opts___] := withOptions[Options[f], {opts},
  (* body of f here... *)
  {x, opt@a, opt@b}
  (* can now call another func with the same option: g[a->opt@a] *)
]

Can anyone see problems with this, or have a better way to do it?

--    --    --    --    --    --    --    --    --    --    --    -- 
Daniel Reeves               http://ai.eecs.umich.edu/people/dreeves/

"In science one tries to tell people, in such a way as to be understood
by everyone, something that no one ever knew before.  In poetry, it's the
exact opposite." -- Paul Dirac (1902-1984)





  • Prev by Date: Re: Summing a list of real numbers
  • Next by Date: List operations "in a given dimension"
  • Previous by thread: Re: Adding columns and rows to a table
  • Next by thread: List operations "in a given dimension"