1
$\begingroup$

I am trying to implement custom options in my code manually, rather than using the built-in Options tools. So I have functions that look like f[x_,y_,opts___] where opts is intended to be a (possibly empty) list or sequence of rules.

I'd like to be able to enter opts as a sequence or list, but I'm having a very hard time getting my code to cover both cases. How can I program my functions so that opts is converted to a list of rules, regardless of whether they are fed into the function as a list or sequence?

$\endgroup$
  • 3
    $\begingroup$ Make it a list then Flatten in case it already was a list, i.e., options = {opts} // Flatten $\endgroup$ – Bob Hanlon Dec 1 '20 at 18:00
  • $\begingroup$ I think this will ruin any options that take lists as values. I.e., suppose I have an option like Range->{0,10}. Won't Flatten ruin this? $\endgroup$ – WillG Dec 1 '20 at 18:02
  • $\begingroup$ Actually it didn't—I guess I just don't understand Flatten $\endgroup$ – WillG Dec 1 '20 at 18:03
  • $\begingroup$ @WillG those rules would still remain in some Rule[a,b] FullForm. $\endgroup$ – CA Trevillian Dec 1 '20 at 18:37
  • $\begingroup$ "trying to implement custom options in my code manually, rather than using the built-in Options tools" - don't. It is a very rare occurrence when you really justifiably need to re-invent the wheel, unless it's for educational purposes. If you think you need a functionality that Options & Co don't cover, then perhaps ask a question about that. I always worry that these questions might stem from an XY problem. $\endgroup$ – MarcoB Dec 1 '20 at 19:11
3
$\begingroup$

OptionsPattern[] does allow entering opts as a sequence or list:

enter image description here

Examples:

ClearAll[f]
f[x_, opts : OptionsPattern[]] := Plot[Sin[x t], {t, 0, Pi}, opts]

Row[{f[5, PlotStyle -> Red, Frame -> True, ImageSize -> 300], 
  f[5, {PlotStyle -> Red, Frame -> True, ImageSize -> 300}], 
  f[5, PlotStyle -> Red, {Frame -> True}, {{{ImageSize -> 300}}}]}, 
 Spacer[10]]

enter image description here

ClearAll[f2]
f2[x_, opts : OptionsPattern[]] := Framed @ Style[x, opts]

Row[{f2["ABC",
     FontColor -> Red, FontSize -> 62, FontFamily -> "French Script MT"], 
 f2["ABC", 
    {FontColor -> Red, FontSize -> 62, FontFamily -> "French Script MT"}], 
 f2["ABC", 
    FontColor -> Red, {{{FontSize -> 62, {{{{ FontFamily -> "French Script MT"}}}}}}}]},
 Spacer[10]]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.