开发者

Matching head different from some pattern

I want to match expression who's head differs from f.

This works开发者_如何学JAVA

[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]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜