Passing options to functions / overriding default options
- To: mathgroup at smc.vnet.net
- Subject: [mg108493] Passing options to functions / overriding default options
- From: Leo Alekseyev <dnquark at gmail.com>
- Date: Sat, 20 Mar 2010 02:45:02 -0500 (EST)
Suppose I have a function foo which is a wrapper for bar. Both of them have certain default options. Options[foo] includes some options that should be passed to bar, which may override some of bar's defaults, but if they are not provided bar should always receive some default options. Here are the definitions ClearAll[foo]; ClearAll[bar]; Options[bar] = {barA -> 1, barB -> 2}; Options[foo] = {barA -> 11, barB -> 22, fooA -> 1}; And here is the desired output: In[199]:= foo[] (* pass some default options to bar *) Out[199]= bar[{barA -> 11, barB -> 22}] In[200]:= foo[barA -> "overriding_barA"] (* overriding the default option barA *) Out[200]= bar[{barA -> "overriding_barA", barB -> 22}] This situation commonly arises for me, and I've been using the following implementation for foo[], which basically concatenates supplied and default options and deletes duplicates, but I keep thinking that there should be a better way. Is there?.. Am I missing something obvious here?.. foo[opts : OptionsPattern[]] := Module[{}, bar[FilterRules[{opts}, Options[bar]]~Join~ FilterRules[Options[foo], Options[bar]] // DeleteDuplicates[#, First[#1] == First[#2] &] &]]