Skip to main content

Functional Pattern Matching for Python

Project description

Splarnektity provides a limited, but valuable, form of functional pattern matching to Python, a la OCaml, Erlang, Haskell, et al.. Another way of thinking of this is: pattern matching over Python lists.

Here is a quick example of Splarnektity’s usage:

from splarnektity import FMatch

sexpr = ('person',
            ('name', 'john'),
            ('address', ('line1', '123 Townville'), ('zip', 54321)),
            ('age', 24),
            ('favorite foods', 'pizza', 'dorritos'),
        )

for x in sexpr[1:]:
    f = FMatch(x)
    V1, V2 = f.var(2)
    if f.when(('name', V1)):
        print 'name:          ', V1.v
    elif f.when(('address', ('line1', V1), ('zip', V2))) and V2.int:
        print 'address line1: ', V1.v
        print 'address zip:   ', V2.v
    elif f.when(('age', V1)) and V1.int:
        print 'age:           ', V1.v
    elif f.when(('favorite foods', V1.others)): # variable length matching
        print 'favorite foods:', V1.v

The result of this example is:

name:           john
address line1:  123 Townville
address zip:    54321
age:            24
favorite foods: ('pizza', 'dorritos')

Project details


Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page