Why does MatchQ[a, r_ /; Head[r] != Plus] evaluate to False?
Why does MatchQ[a, r_ /; Head[r] != Plus] evaluate to False?
I'm trying to understand. Why is it that:
MatchQ[a, r_ /; Head[r] != Plus]
Evaluates to:
False
? For me, I would think that, because:
Head[a]
Evaluates to:
Symbol
Where a has no value or expression assigned to it, then this:
a
MatchQ[a, r_ /; Head[r] != Plus]
Should evaluate to True. Could someone point me in the right direction to understanding this better? Thanks!
True
1 Answer
1
The problem is this:
If a is a symbol then its Head is Symbol, so Head[a] != Plus reduces to Symbol != Plus. Unequal (!=) is supposed to be a mathematical test for inequality. In this case, it just cannot decide whether Symbol != Plus should evaluate to True or to False, since both sides are Symbols. Here an example why this is undecidable with the current amount of information:
a
Head
Symbol
Head[a] != Plus
Symbol != Plus
Unequal
!=
Symbol != Plus
True
False
Symbol
With[Symbol = 1, Plus = 1, Symbol != Plus]
With[Symbol = 1, Plus = 0, Symbol != Plus]
False
True
So the expression Symbol != Plus stays unevaluated. (This is the best strategy since later definitions could make it decidable.)
Symbol != Plus
Because the second argument of Condition (/;) does not evaluate to True, the pattern does not match.
Condition
/;
True
Lesson to learn: For testing for structual inequality, use UnsameQ (=!=):
UnsameQ
=!=
MatchQ[a, r_ /; Head[r] =!= Plus]
True
Of course, the same applies, mutatis mutandis, to Equal and SameQ.
Equal
SameQ
Thanks for contributing an answer to Mathematica Stack Exchange!
But avoid …
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy