I am looking for a pattern that matches a (possibly empty) list consisting of identical (in the sense of Equal[]) atomic objects, but I can't figure it out. Any help would be greatly appreciated开发者_StackOverflow中文版.
All of the responses so far seem to have missed the requirement that the objects being matched need to be atomic. The following does this:
Cases[testList, {a___?AtomQ} /; Equal[a]]
If you don't define identical in the sense of Equal
you could have used:
Cases[testList, {(a_?AtomQ) ...}]
With a slightly modified test list you'll see other methods fail the requirement
testList = {{1, 1.0, 1.0}, {a, b, c}, {Exp[Pi] + 1, Exp[Pi] + 1, Exp[Pi] + 1}, {}, {3}};
they all incorrectly match the 3rd element too.
Does this work for you?
testList = {
{1, 1.0, 1.},
{a, b, c},
{0, Exp[Pi*I] + 1.0, Sin[Pi]}
}
Cases[testList, _List?(Equal @@ # &)]
Using Condition
, instead of PatternTest
:
In[31]:= testList = {{1, 1.0, 1.}, {a, b, c}, {0, Exp[Pi*I] + 1.0,
Sin[Pi]}, {}, {3}};
Cases[testList, {a___} /; Equal[a]]
Out[32]= {{1, 1., 1.}, {0, 0., 0}, {}, {3}}
(and expanding on Mark's list of test cases to cover empty and singleton lists.)
精彩评论