Skip to main content

Pattern to match a non-empty list of non-empty lists



Is there a pattern to match a list of lists, containing at least one list, with each list containing at least one element?


In the Mathematica documentation it says that the pattern


x:{___List}

will match a list of lists. This is true, but it also matches {}, which is a list of zero lists (or zero anything). To make sure there is at least one list in my list of lists I can remove one of the underscores to change BlankNullSequence to BlankSequence, i.e. switch to


x:{__List}

which no longer matches {}. It does, however, match {{}}. How can I also guarantee that each matched sublist is non-empty? Is this even possible, or should I be checking for it programmatically within the Module to which I'm passing arguments of this form?



Answer



If I am understanding you:



x : {{__} ..}

See Repeated for more information and additional options. Also see RepeatedNull while you're there.


Make sure you understand BlankSequence and Pattern as well.




Here is a breakdown of the expression above. First let us view the FullForm which is as close to the way Mathematica sees it as possible:


FullForm[ x:{{__}..} ]


Pattern[x,

List[
Repeated[
List[
BlankSequence[]
]
]
]
]

This expanded form is useful to remove any ambiguity in Mathematica's parsing.



Therefore from the inside out we have (short form : long form : description):


__ : BlankSequence[] : one or more arguments with any head


{ } : List[ ] : inside the head List


.. : Repeated[ ] : one or more arguments matching the given pattern


{ } : List[ ] : inside the head List


x: : Pattern[x, ] : a unique expression that matches the given pattern, named x


Pay attention to this last point: naming the pattern changes the way it behaves, such that it represents a unique expression. Consider this superficially similar pattern:


x : {{a__} ..}

This will only match e.g. {{1, 2}, {1, 2}, {1, 2}} but not {{1, 2}, {3}, {4, 5, 6}} because by naming the first sequence 1, 2 all other sequences must be identical. Simply matching the pattern a__ independently is not enough.



Comments