Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern to match list of identical elements

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.

like image 721
reddish Avatar asked Jun 23 '11 00:06

reddish


2 Answers

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.

like image 93
Sjoerd C. de Vries Avatar answered Nov 10 '22 07:11

Sjoerd C. de Vries


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 @@ # &)]
like image 22
Mark McClure Avatar answered Nov 10 '22 08:11

Mark McClure