Are there pattern matching functions in Python like this?
Asked Answered
G

4

6

I just found the pattern matching feature 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 similar syntax sugar or library to do that in Python?

Googol answered 10/8, 2012 at 21:44 Comment(0)
C
3

No there is not, python's pattern matching is only iterable unpacking like this:

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

Or in 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 of external libraries that realize pattern matching.

Chromatograph answered 10/8, 2012 at 21:48 Comment(0)
F
1

If your willing to go towards python-based languages (even if they're not strictly python), then you might like Coconut.

Cocunut adds several features to Python for functional programming, 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)
Feverfew answered 18/1, 2019 at 3:10 Comment(0)
C
1

2020 is coming, I'd say https://github.com/thautwarm/moshmosh

You can use it in this way:

  • in main.py

    import moshmosh
    import mypackage
    
  • in some module of mypackage

    # +pattern-matching
    with match([1, [2, (3, 4)]]): 
     if [a, [2, (_, 4)]]: 
         print(a) # print 1
    

IPython is supported as well.

And pattern matching from moshmosh is extensible(__match__ for making new patterns) and fast(shouldn't be slower than the hand-written).

Chickie answered 20/11, 2019 at 4:6 Comment(0)
A
0

Python does not have a built-in pattern matching feature, but there are some libraries for Python that implement pattern-matching using unification.

Based on your first example, it is possible to match a pattern using the unification library:

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.")
Alien answered 18/1, 2019 at 0:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.