Options and FilterOptions

*To*: mathgroup at christensen.cybernetics.net*Subject*: [mg946] Options and FilterOptions*From*: Allan Hayes <hay%haystack at christensen.cybernetics.net>*Date*: Wed, 3 May 1995 00:25:30 -0400

Here are some general points about options and the function FilterOptions that might be of use. 1) Options can be of the form name:> value as well as name->value . So, one should normally use the form foo[___, opts___?OptionQ] 2) Nested list of options are accepted by OptionQ In[1]:= OptionQ[{a->b,{{x :> y}}}] Out[1]= True and by other functions: eg In[2]:= Plot[x,{x,0,1}, {Frame ->True}]; They can appear, or be generated, in code (though with care we could probably avoid this). Unfortunately we find 2a) A problem with ReplaceAll In[3]:= {a,x}/.{a->b,{{x :> y}}} ReplaceAll::rmix: Elements of {a -> b, {{x :> y}}} are a mixture of lists and non-lists. Out[3]= {a, x} /. {a -> b, {{x :> y}}} Solution: use expr/.Flatten[{opts}]/.Options[foo] (We don't need to use Flatten[Options[symbol]]] since even if we define In[4]:= Options[foo] = {{a->b},{{c->d}}}; Which is probably undesirable, we still get In[5]:= Options[foo] Out[5]= {a -> b, c -> d} ) 2b) A problem with FilterOptions and lists of options. In[6]:= Needs["Utilities`FilterOptions`"] In[8]:= FilterOptions[Plot, {PlotPoints -> 10,Frame->True}] Function::fpct: Too many parameters in {FE`e} to be filled from Function[{FE`e}, LinkWrite[$ParentLink, <<1>>], {HoldAll}][]. Out[7]= Sequence[] This is not what we wanted; which was Sequence[PlotPoints -> 10, Frame -> True] Solution: use FilterOptions[symbol, Sequence@@Flatten[{opts}]] In[8]:= FilterOptions[Plot, Sequence@@Flatten[{{PlotPoints -> 10,Frame->True}}]] Out[8]= Sequence[PlotPoints -> 10, Frame -> True] Or we could temporarily define In[9]:= FilterOptions2[foo_Symbol,opts___?OptionQ]:= FilterOptions[foo, Sequence@@Flatten[{opts}] ] Of course, this trick could be built into a new version of FilterOptions. Finally: Messages are generated in the next two examples but they can be ignored as the answers are correct In[11]:= FilterOptions[Plot, Sequence@@Flatten[{a->b}]] Function::fpct: Too many parameters in {FE`e} to be filled from Function[{FE`e}, <<1>>, {HoldAll}][]. Out[10]= Sequence[] In[12]:= FilterOptions[Plot, Sequence@@Flatten[{}]] Function::fpct: Too many parameters in {FE`e} to be filled from Function[{FE`e}, <<1>>, {HoldAll}][]. Out[11]= Sequence[] These messages are caused by the attempted evaluation of Sequence[] (which is returned unevaluated): In[13]:= Sequence[] Function::fpct: Too many parameters in {FE`e} to be filled from Function[{FE`e}, <<1>>, {HoldAll}][]. Out[12]= Sequence[] Allan Hayes hay at haystack.demon.uk