I want to match expression who's head differs from f.
This works
[In] !MatchQ[t[3], x_ /; Head[x] == f]
[Out] True
But not this
[In] MatchQ[t[3], x_ /; Head[x] != f]
[Out] False
Why does the second solution not work? How can I make it work?
Why this does not work: you must use =!=
(UnsameQ
), rather than !=
(Unequal
) for structural comparisons:
In[18]:= MatchQ[t[3],x_/;Head[x]=!=f]
Out[18]= True
The reason can be seen by evaluating this:
In[22]:= Head[t[3]]!=f
Out[22]= t!=f
The operators ==
(Equal
) and !=
(Unequal
) do evaluate to themselves, when the fact of equality (or inequality) of the two sides can not be established. This makes sense in a symbolic environment. I considered this topic in more detail here, where also SameQ
and UnsameQ
are discussed.
There are also more elegant ways to express the same pattern, which will be more efficient as well, such as this:
MatchQ[t[3],Except[_f]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With