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$
5
  • $\begingroup$ What is the expected result? Unevaluated input? $\endgroup$
    – Kuba
    Commented Feb 1, 2019 at 14:34
  • $\begingroup$ @kuba I expected g[2, {}, "asd" -> 4] $\endgroup$
    – MeMyselfI
    Commented Feb 1, 2019 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
    Commented Feb 1, 2019 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.
    Commented Feb 1, 2019 at 14:58
  • 1
    $\begingroup$ Possible duplicate of Extra empty lists as function arguments $\endgroup$
    – MarcoB
    Commented Feb 5, 2019 at 4:45

1 Answer 1

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.