# Why does Repeated not work in this case?

I think I don't understand how to use Repeated.

I have a list for example

list={a,b,a,b,a,b,a,a,b}


I want to detect whether this list has repeated element a,a or b,b

I tried

Cases[list, Repeated[a,{2}]]


It doesn't work, why? How to do this?

• Think about it - what are the cases that are tested? It's the elements of the list. Try, e.g., Cases[list, x_ /; (Print@x; True)] and see what you get. Cases[Split@list, {Repeated[a | b, {2}]}] will spit out a list of matches, MemberQ[Split@list, {Repeated[a | b, {2}]}] will return True or False if any are there (you said "detect", hence I'm guessing that's what you meant.) There are other ways, that should get you started. – ciao May 28 '16 at 5:46
• @ciao Thank you very much. I got the point – matheorem May 28 '16 at 5:57
• @ciao Might be good to post that comment as an answer. Else the question could get closed. Strikes me as the sort of thing that can be confusing and so maybe ought to be kept, with a response of course. – Daniel Lichtblau May 28 '16 at 15:38
• @DanielLichtblau : done. – ciao May 28 '16 at 18:58

Per request by the Pope:

Think about it - what are the cases that are tested?

It's the elements of the list.

Try, e.g., Cases[list, x_ /; (Print@x; True)] and see what you get (it will show that the test is done on an element-by-element basis).

Cases[Split@list, {Repeated[a | b, {2}]}] will spit out a list of matches, MemberQ[Split@list, {Repeated[a | b, {2}]}] will return True or False if any are there (you said "detect", hence I'm guessing that's what you meant.)

There are other ways, that should get you started.

Btw- putting a Print (or Sow, etc.) temporarily as part of a test/rule/etc. can be a quite handy debugging and learning tool - I use it every now and then when a complex rule and/or test is not doing what I think it should (and inevitably, it's my thinking that was off).

Why part is explained nicely in @ciao's answer. This post deals with the part:

I want to detect whether this list has repeated element a,a or b,b

You can get what you expected to get from Cases[...] using the new-in-v-10 function SequenceCases:

list={a,b,a,b,b,b,a,b,a,a,b};
SequenceCases[list,{Repeated[x_,{2}]}]


{{b, b}, {a, a}}

Or, define a Boolean function that returns True when the input list contains repeated elements:

containsRepeatedQ = SequenceCases[#,{Repeated[x_,{#2}]}] != {}&;

containsRepeatedQ[{a,b,a,b,a,b,a,b}, 2]


False

containsRepeatedQ[{a,b,a,b,a,b,a,a,b}, 2]


True

• Hi, kglr. Thank you introducing this new feature! Very useful – matheorem May 29 '16 at 2:06