# How to match a sequence of complex patterns?

I have list with the form {{a1,b1}->{x1,y1},{a2,b2}->{x1,y2},...} where the {ai,bi}'s can be {}. I know the elements of the list can be matched by {___} -> {_, _}, but I don't know how to match a list of this form. So how can I match it?

UPDATE: I meant a pattern test: To test whether a list is in this form

We needn't use Map and Apply as in ziyuang's answer. We can make use of PatternSequence with Repeated (..) or RepeatedNull (...) instead, e.g.

list = {{a1, b1} -> {x1, y1}, {} -> {x3, y3}, {a2, b2} -> {x1, y2},
{} -> {x6, y6}, {} -> {x5, y5}, {} -> {x0, y0}, {a3, b3} -> {x3, y3},
{a4, b4} -> {x4, y4}};


Now we can test various approaches :

{ MatchQ[ #, { PatternSequence[{___} -> {_, _}] ..}]& @ list,
MatchQ[ #, {({PatternSequence[]} | {_, _} -> {_, _}) ..}]& @ list,
MatchQ[ #, {({PatternSequence[___]} -> {_, _}) ..}]& @ list }

{True, True, True}


The advantage of PatternSequence is seen when we'd like to deal with more sophisticated cases of pattern matching.

• I think PatternSequence[{___} -> {_, _}] can be substituted by ({___} -> {_, _}) Commented Apr 11, 2012 at 22:37
• @ziyuang What did you mean ? Try MatchQ[#, ({___} -> {_, _})] &@ list and you should get False. Commented Apr 11, 2012 at 22:44
• ({___} -> {_, _}).., of course. Commented Apr 11, 2012 at 23:13
• @ziyuang With PatternSequence you can match a broad range of sequences, intermediate ones with respect to very general x__ and very specific x... Commented Apr 12, 2012 at 13:29

The pattern to match a list of zero or more such terms is

List[({___}->{_,_})...]


If you want to only match if there's at least one entry in the list, use one dot less:

List[({___}->{_,_})..]


So to test that list has that form, use (assuming an empty list is allowed)

MatchQ[list, List[({___}->{_,_})...]]


and to define a function accepting only such lists, write

f[x:List[({___}->{_,_})...]] := somethingUsing[x]

• Though I choose @Artes 's reply as the answer, yours is also very helpful, Thank you~ Commented Apr 13, 2012 at 20:15

I've found it myself. Use And@@(MatchQ[#,{___} -> {_, _}]&/@theList)

{{a1, b1} -> {x1, y1}, {a2, b2} -> {x1, y2}} /.  HoldPattern[{___} -> {_, _}] -> "your match"

• I meant a pattern test. Commented Apr 11, 2012 at 21:54