5
$\begingroup$

OptionsPattern was introduced in Mathematica v6 so I have finally decided to give a try.

Look at this program:

Clear@foo;
foo[options : OptionsPattern[]] := {options}
foo[k2 -> 3]
foo[Indexed[k, 2] -> 3]

out:

{k2 -> 3}
foo[Indexed[k, {2}] -> 3]

The rule with compound left hand side has not matched OptionsPattern[].

You can replace Indexed by any function (Power, Subscript), it will be the same.

Now compare with old style option pattern:

Clear@foo;
foo[options___Rule] := {options}
foo[k2 -> 3]
foo[Indexed[k, 2] -> 3]

out:

{k2 -> 3}
{Indexed[k, {2}] -> 3}

Matching occurs in all cases.

Is there a bug in OptionsPattern?

$\endgroup$
1
  • 1
    $\begingroup$ It may be the same sort of limitation that prevents using compound expression as variable in Manipulate or Plot. $\endgroup$ Feb 12 '21 at 0:39
8
$\begingroup$

The whole question is based on the wrong premise that old-style options were just simply arbitrary rules. This is not the case, in the past the special OptionQ predicate was used to distinguish options from general rules.

With proper option-testing, your example would look like:

Clear@foo;
foo[options___Rule?OptionQ] := {options}
foo[k2 -> 3]
foo[Indexed[k, 2] -> 3]

which gives the output identical to what OptionsPattern[] method does.

$\endgroup$
1
  • $\begingroup$ Yes, I was abusing the option system to pass arbitrary rules. It is not a bug, it is a feature. $\endgroup$ Feb 12 '21 at 10:26
4
$\begingroup$

When OptionsPattern[] is used, OptionValue@k2 is supposed to work too, so behind the scene there is something like

k2/:OptionValue@k2=3

which fails if k2 is replaced by f1[k2]: you would get a "Tag too deep" error.

So the new system has simpler syntax but is less general.

$\endgroup$
3
  • $\begingroup$ See also mathematica.stackexchange.com/questions/174544/… $\endgroup$ Feb 12 '21 at 1:12
  • 4
    $\begingroup$ Doesn't really explain String options, since they cannot be used with TagSet. Option names were originally Symbol. Then they seemed to realize that the expansion of functions and their options might flood the system namespace with an overwhelming number of symbols. So they expanded to allow String option names. Those are the only alternatives in system commands. $\endgroup$
    – Michael E2
    Feb 12 '21 at 1:50
  • $\begingroup$ Yes indeed OptionQ["method" -> xx] returns True so my explanation cannot be complete. $\endgroup$ Feb 12 '21 at 10:32

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.