pattern matching - `Plus` wrongly applies `OneIdentity` to eradicate itself in `Plus[Power[_, 2] ..]`, unreproducible
I was trying to match some polynomials, but this is weird:
Plus[Power[x, 2], Power[y, 2]]~MatchQ~Plus[Power[_, 2] ..]
SetAttributes[f, Attributes@Plus]
f[Power[x, 2], Power[y, 2]]~MatchQ~f[Power[_, 2] ..]
Despite f having all of the same attributes as Plus, the expressions match only when it is used
FalseTrue
I found this is the root of the problem:
Plus[Power[_, 2] ..] // FullForm
gives Repeated[Power[Blank[],2]], the Plus entirely disappears, while
f[Power[_, 2] ..] // FullForm
gives f[Repeated[Power[Blank[],2]]] as I would expect.
I understand many built-in symbols escape the standard evaluation procedure anyways, so that not all of their behaviour is readily understandable from their Attributes etc. Obviously, Plus wrongly applies something like OneIdentity in this case, causing it to be removed. A user-defined symbol such as f doesn't do it here.
Is this a bug?
Answer
As pointed out in comments, this is caused by
Plus[x]isx
Here are some workarounds
Plus[Power[x, 2], Power[y, 2]]~MatchQ~Verbatim[Plus][Power[_, 2] ..]
Plus[Power[x, 2], Power[y, 2]]~MatchQ~HoldPattern[Plus][Power[_, 2] ..]
Plus[Power[x, 2], Power[y, 2]]~MatchQ~HoldPattern[Plus[Power[_, 2] ..]]
all giving True as expected.
Comments
Post a Comment