3
$\begingroup$

I'm totally surprised by the finding I had never noticed before. This code works as obviously intended

Quiet[Remove[funct]];
Options[funct] = {fA -> "A", fB -> "B"};
funct[] := "error: no arguments";
funct[x_, OptionsPattern[]] := "NOT a string!";
funct[x_?StringQ, OptionsPattern[]] := {x, OptionValue[fA], 
   OptionValue[fB]};
funct[x_, y__, OptionsPattern[]] := "error: more than one arguments";
funct[]
funct[1, 2]
funct[1]
funct["z"]
funct["z", fA -> "a"]
funct["z", fA -> "a", fB -> "b"]

and returns:

error: no arguments
error: more than one arguments
NOT a string!
{z,A,B}
{z,a,B}
{z,a,b}

This one differes from the previous only by a switch of lines in function's definition.

Quiet[Remove[funct]];
Options[funct] = {fA -> "A", fB -> "B"};
funct[] := "error: no arguments";
funct[x_, y__, OptionsPattern[]] := "error: more than one arguments";
funct[x_, OptionsPattern[]] := "NOT a string!";
funct[x_?StringQ, OptionsPattern[]] := {x, OptionValue[fA], 
   OptionValue[fB]};
funct[]
funct[1, 2]
funct[1]
funct["z"]
funct["z", fA -> "a"]
funct["z", fA -> "a", fB -> "b"]

This reversal should not (in my evidently wrong knowledge ...) alter the evaluation process in any way, on the contrary the result is totally different

error: no arguments
error: more than one arguments
NOT a string!
{z,A,B}
error: more than one arguments
error: more than one arguments

Please, can you elucidate the reason ?

$\endgroup$
  • $\begingroup$ Order matters, but in general order is not important because MMA always uses patterns from least general to most general. When patterns are judged as "equally general", only then does order matter. $\endgroup$ – Manuel --Moe-- G Dec 2 '16 at 17:18
  • $\begingroup$ Thanks for the reply ! What's the criterion to decide when patterns are "equally general" ? $\endgroup$ – mitochondrial Dec 2 '16 at 17:29
  • 1
    $\begingroup$ my understanding is that this criterion is part of the proprietary low-level implementation and not under our power to examine or change. $\endgroup$ – Manuel --Moe-- G Dec 2 '16 at 17:37
  • 3
    $\begingroup$ Related - How is pattern specificity decided? $\endgroup$ – Simon Woods Dec 2 '16 at 22:05

Your Answer

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

Browse other questions tagged or ask your own question.