Message Boards Message Boards

0
|
3368 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

Trying to get Repeated, or .., to correctly match a subsequence

Posted 11 years ago
I am seeing a variety of problems which could be simply and compactly solved if a particular sequence satisfying some conditions could be extracted from a list. Repeated or .. looks like a good candidate. An example problem that was posted recently could easily be done if it was possible to extract the leading sequence of sublists that begin with the same element, so I try to extract all but the last two items:
In[1]:= l = {{1, 2}, {1, 3}, {1, 2}, {2, 1}, {1, 2}};

l /. {x : Repeated[{a_, _}], y__} -> x

Out[2]= {1, 2}
which I assumed would match as many copies as possible of {a_,_} against the beginning of the list, match the remainder with y and give me the subsequence named x.
 
Then I try
In[3]:= l = {{1, 2}, {1, 3}, {1, 2}, {2, 1}, {1, 2}};

l /. x : Repeated[{a_, _}] -> {x}

Out[4]= {{{1, 2}}, {{1, 3}}, {{1, 2}}, {{2, 1}}, {{1, 2}}}
and I try lots of other variations of this, none of which name the subsequence x and replace the original list with the desired subsequence or even seem to match the subsequence of repeated elements and nothing else.

The documentation says "If the pattern contains named parts, then each instance of these parts must be identical." which seems to be exactly what I am trying to accomplish for this problem.

I have done my usual read the help pages and try lots of variations followed by repeated Google searches for good keywords to try to find examples of someone else having figured this out, but searching for .. or the word Repeated doesn't turn up many relevant results, as expected.

Is there a page anywhere that greatly and clearly expands on the correct and successful use of Repeated with named patterns?

I do understand I could forget trying to use Repeated and/or attack this problem in at least half a dozen other different ways, but I'm trying to understand how to use Repeated to substantially increase the power of my pattern matching toolkit.

Thank you
POSTED BY: Bill Simpson
Hi Bill,

you have to use Longest to force it to take the longest:
l = {{1, 2}, {1, 3}, {1, 2}, {2, 1}, {1, 2}};
l /. {x : Longest[Repeated[{a_, _}]], y__} :> {x}
giving:
{{1, 2}, {1, 3}, {1, 2}}

You need to output {x} rather than x because x will be a sequence.
POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract