This is a rewording of the question. The original post is below.
How come that a pattern for an expression with a specific head is not more specific than a pattern for an expression with a generic head?
The code below provides the example. The original wording of the question includes references to "evaluation procedure" in an effort to make the case that the order in which Mathematica tried the patterns is not what I expected.
According to The Ordering of Definitions:
[Mathematica] follows the principle of trying to put more general definitions after more specific ones.
Also, from The Standard Evaluation Procedure
In the standard evaluation procedure, [Mathematica] first evaluates the head of an expression and then evaluates each element of the expression …
With that in mind, consider the following code:
Clear[h];
h /: _[___, _h, ___] := "Pattern 2";
h /: f[_h, ___] := "Pattern 1";
f[h[1]]
(*"Pattern 2"*)
In my understanding of the two quotes above, the output should be "Pattern 1". My reasoning is that when patterns are evaluated, their heads are evaluated first and f
is less general than _
.
From this answer, I gather that those two patterns are incomparable:
Internal`ComparePatterns[_[___, _h, ___], f[_h, ___]]
(*Incomparable*)
That explains the "Pattern 2" outcome. I need help to catch the error in my reasoning though.
Update to address a comment.
The answers in a previous question suggest
[the algorithm used internally for pattern ordering] might forever remain an implementation secret, like the 'canonical order'.
Even if that is true, that secret implementation should conform to the published documents. Hence my question is whether there are any flaws in my reasoning. For example, it might be possible that pattern evaluation does not follow The Standard Evaluation Procedure. If so, is there some documentation about it? If there is no error in my previous statement
when patterns are evaluated, their heads are evaluated first and f is less general than _
does the code above show a bug?
_[___, _h, ___]
first, that's the one it matches to. The blurb aboutHeads
being evaluated first just means thatf
evaluates first in your example before all else. Look: try adding the definitionf = HoldComplete
in your example, and you'll seef
gets swapped out forHoldComplete
before anything; and that stops yourUpValues
onh
from working. $\endgroup$