Are there template matching functions in Python?

I just found pattern matching in Racket very powerful.

> (match '(1 2 3) [(list a b c) (list c b a)])

'(3 2 1)

> (match '(1 2 3) [(list 1 a ...) a])

'(2 3)

> (match '(1 2 3)
    [(list 1 a ..3) a]
    [_ 'else])

'else

> (match '(1 2 3 4)
    [(list 1 a ..3) a]
    [_ 'else])

'(2 3 4)

> (match '(1 2 3 4 5)
    [(list 1 a ..3 5) a]
    [_ 'else])

'(2 3 4)

> (match '(1 (2) (2) (2) 5)
    [(list 1 (list a) ..3 5) a]
    [_ 'else])

'(2 2 2)

Is there any similar syntactic sugar or library for this in Python?

+5
source share
3 answers

No, no, python pattern matching is just iterative unpacking like this:

>>> (x, y) = (1, 2)
>>> print x, y
1 2

Or in a function definition:

>>> def x((x, y)):
    ...

Or in python 3:

>>> x, *y = (1, 2, 3)
>>> print(x)
1
>>> print(y)
[2, 3]

But there are some external libraries that implement pattern matching.

+3
source

Python , Python, .

, :

from unification import *

a,b,c = var('a'),var('b'),var('c')
matched_pattern = unify([1,2,3],[var('a'),var('b'),var('c')])
if(matched_pattern):
    second_pattern = [matched_pattern[c],matched_pattern[b],matched_pattern[a]]
    print(second_pattern)
else:
    print("The pattern could not be matched.")
0

If you want to switch to Python-based languages ​​(even if they are not strictly Python), then you might like Coconut.

Cocunut adds several functions for functional programming in Python, including pattern matching.

case [1,2,3]:
    match (a,b,c):
        print((c,b,a))
# (3,2,1)

case [1,2,3]:
    match (1,) + a:
        print(a)
# (2, 3)

case [1,2,3]:
    match (1,) + a if len(a) == 3:
        print(a)
else:
    print("else")
# else

case [1,2,3,4]:
    match (1,) + a if len(a) == 3:
        print(a)
else:
    print("else")
# (2,3,4)

case [1,2,3,4,5]:
    match (1,) + a + (5,) if len(a) == 3:
        print(a)
else:
    print("else")
# (2,3,4)
0
source

All Articles