与某些图案不同的匹配头

发布于 2024-12-08 10:32:22 字数 250 浏览 3 评论 0原文

我想匹配 who's head 与 f 不同的表达式。

这可行

[In]  !MatchQ[t[3], x_ /; Head[x] == f]
[Out] True

但不行

 [In]  MatchQ[t[3], x_ /; Head[x] != f]
 [Out] False

为什么第二个解决方案不起作用?我怎样才能让它发挥作用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一绘本一梦想 2024-12-15 10:32:22

为什么这不起作用:您必须使用 =!= (<代码>UnsameQ),而不是!= (不相等)用于结构比较:

In[18]:= MatchQ[t[3],x_/;Head[x]=!=f]
Out[18]= True

通过计算可以看出原因:

In[22]:= Head[t[3]]!=f
Out[22]= t!=f

运算符== (Equal) 和 != (不相等) 当双方相等(或不相等)的事实无法成立时,会对自身求值。这在象征性环境中是有意义的。我在此处更详细地考虑了这个主题,其中还有SameQ 和 UnsameQ

还有更优雅的方式来表达相同的模式,这也会更有效,例如:

MatchQ[t[3],Except[_f]]

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]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文