Simple and convenient python library dedicated to Pattern Matching
If you want to manipulate object based on types in Python the dedicated design pattern is the visitor. Unfortunately even if such pattern is well known its implementation is always painful because it implies code dissemination.
In addition such mechanism only enables selection based on types and does not provides a simple and intuitive mechanism filtering objects using their values i.e. attributes.
For this purpose a simple pattern matching inspired by Scala extractor object has been designed.
Then pattern matching cases can be done on the object kind and it's internal state. For instance the following sample checks if an integer is O or not.
from smallibs.suitcase.cases import _
from smallibs.suitcase.match import Match
isZero = Match.match();
isZero.caseOf(0).then(True);
isZero.caseOf(_).then(False);
isZero.match(0); # == True
Computation based on structural induction can be recursive.
from smallibs.suitcase.cases import var
from smallibs.suitcase.cases.list import Empty,Cons
from smallibs.suitcase.match import Match
adder = Match.create()
adder.caseOf(Empty).then(0)
adder.caseOf(Cons(var,var)).then(lambda i:i[0] + adder.match(i[1]))
adder.match([1,2,3]) # == 6 (A perfect number)
Computation based on structural induction can also been provided using
reentrant
capability for example.
from smallibs.suitcase.cases import var,reentrant
from smallibs.suitcase.cases.list import Empty,Cons
from smallibs.suitcase.match import Match
adder = reentrant(Match.create())
adder.caseOf(Empty).then(0)
adder.caseOf(Cons(var,var.of(adder))).then(lambda i:i[0] + i[1])
adder.match([1,2,3]) # == 6 (A perfect number)
Since Python offers hight level capabilities like infix definitions the previous example can be expressed naturally.
from smallibs.suitcase.cases import var,reentrant
from smallibs.suitcase.cases.list import Empty,Cons
from smallibs.suitcase.match import *
adder = reentrant(Match.create())
adder <<case>> Empty <<then>> 0 \
<<case>> Cons(var,var.of(adder)) <<then>> (lambda i:i[0] + i[1])
adder.match([1,2,3]) # == 6 (A perfect number)