6
$\begingroup$

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

$\endgroup$

4 Answers 4

6
$\begingroup$

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.

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

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]
$\endgroup$
1
  • $\begingroup$ Though I choose @Artes 's reply as the answer, yours is also very helpful, Thank you~ $\endgroup$
    – Ziyuan
    Commented Apr 13, 2012 at 20:15
4
$\begingroup$

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

$\endgroup$
2
$\begingroup$
{{a1, b1} -> {x1, y1}, {a2, b2} -> {x1, y2}} /.  HoldPattern[{___} -> {_, _}] -> "your match"
$\endgroup$
1
  • $\begingroup$ I meant a pattern test. $\endgroup$
    – Ziyuan
    Commented Apr 11, 2012 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.