5
$\begingroup$

I don't understand the output from:

Remove[g];
Options[g] = {"asd" -> 2};
g[a_, Optional[z_?Positive, 1], OptionsPattern[]] := {a, z, OptionValue["asd"]}

g[2, {}, "asd" -> 4]

{2, 1, 4}

The documentation of PatternTest says:

Any result for test[pval] other than True is taken to signify failure

but Positive[{}] =!= True holds, so it appears that the { } argument is interpreted as an option although the head is not Rule. I'm not sure how this should be fixed because I don't understand why it is wrong as it stands. What am I missing?

$\endgroup$

closed as off-topic by Michael E2, Bill Watts, Alex Trounev, MarcoB, bbgodfrey Feb 9 at 19:47

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Michael E2, Bill Watts, Alex Trounev
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ What is the expected result? Unevaluated input? $\endgroup$ – Kuba Feb 1 at 14:34
  • $\begingroup$ @kuba I expected g[2, {}, "asd" -> 4] $\endgroup$ – MeMyselfI Feb 1 at 14:35
  • 2
    $\begingroup$ I am not sure I understand, {} fails Positive test so optional 1 is used, what is the problem? Sorry if I missed something $\endgroup$ – Kuba Feb 1 at 14:39
  • 5
    $\begingroup$ @m_goldberg - I feel like questions where the user misunderstands how Mathematica works are specifically on-topic here. For this question, closing as duplicate of Extra empty lists as function arguments might be appropriate, so that the next time someone gets confused about this and their search results bring them here, they get directed to a helpful answer. $\endgroup$ – Jason B. Feb 1 at 14:58
  • 1
    $\begingroup$ Possible duplicate of Extra empty lists as function arguments $\endgroup$ – MarcoB Feb 5 at 4:45
5
$\begingroup$

O.k. from the comments and the OptionsPattern documentation:

Any nesting of empty lists will match OptionsPattern

I understand now why the pattern matched against my expectation. To make it stop and behave the way I originally had in mind, the last argument (OptionsPattern[]) must be replace by

e : OptionsPattern[] /; MatchQ[Unevaluated[e], Repeated[_Rule | _RuleDelayed]]

After realizing that nested lists are intended as a valid way to specify options, however, it makes more sense to just keep things as in the OP.

$\endgroup$

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