Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching head different from some pattern

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?

like image 608
sjdh Avatar asked Oct 05 '11 12:10

sjdh


1 Answers

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]]
like image 136
Leonid Shifrin Avatar answered Oct 07 '22 12:10

Leonid Shifrin