8
$\begingroup$

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:

MatchQ[a, r_ /; Head[r] != Plus]

Should evaluate to True. Could someone point me in the right direction to understanding this better? Thanks!

$\endgroup$
15
$\begingroup$

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:

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.)

Because the second argument of Condition (/;) does not evaluate to True, the pattern does not match.

Lesson to learn: For testing for structual inequality, use UnsameQ (=!=):

MatchQ[a, r_ /; Head[r] =!= Plus]

True

Of course, the same applies, mutatis mutandis, to Equal and SameQ.

$\endgroup$

Your Answer

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

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