Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structural pattern for variable number of elements of a specific type

As a toy example, let's say I wanted to match a sequence of 1 integer, an unknown number of strings, and then 1 boolean. Is that currently possible with the match statement?

If the number of strings is known in advance the problem is trivial, for 2 strings it's just:

match val:
    case [int(), str(), str(), bool()]:
        ...

But can it be done for n strings?

My immediate intuition was to try something like:

match val:
    case [int(), *str(), bool()]:
        ...

But this is a SyntaxError.

Is this currently something that just can't be done with pattern matching?

like image 958
matthewgdv Avatar asked Nov 19 '25 21:11

matthewgdv


1 Answers

You can use a guard:

match val:
  case [int(), *v, bool()] if all(isinstance(i, str) for i in v): 
     print('matched')
like image 164
Ajax1234 Avatar answered Nov 21 '25 11:11

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!