How to implement Varient/Tagged Unions/Pattern Matching in Python?

M

metal

I want to get pattern matching like OCaml in python(ref:http://
en.wikipedia.org/wiki/Tagged_union)

I consider the syntax:

def decl():
def Plus(expr, expr): pass
def Minus(expr, expr): pass
def Times(expr, expr): pass
def Divide(expr, expr): pass
def Value(str): pass
@enum
def expr(Plus, Minus, Times, Divide, Value): pass
declare_types(locals())

def f(e):
def _Plus(l, r):
return '(%s+%s)' % (l, r)
def _Minus(l, r):
return '(%s-%s)' % (l, r)
def _Times(l, r):
return '(%s*%s)' % (l, r)
def _Divide(l, r):
return '(%s/%s)' % (l, r)
def _Value(x):
return x
try:
match(e, locals()) # visitor pattern
except NoMatchedError:
pass
(n*(x+y))


But it's hard to do with nested matching. Any suggestions would be
appreciated


BTW, Please don't ask "Why do you want to do like this"
 
A

Aahz

I want to get pattern matching like OCaml in python(ref:http://
en.wikipedia.org/wiki/Tagged_union)

I consider the syntax:

def decl():
def Plus(expr, expr): pass
def Minus(expr, expr): pass
def Times(expr, expr): pass
def Divide(expr, expr): pass
def Value(str): pass
@enum
def expr(Plus, Minus, Times, Divide, Value): pass
declare_types(locals())

def f(e):
def _Plus(l, r):
return '(%s+%s)' % (l, r)
def _Minus(l, r):
return '(%s-%s)' % (l, r)
def _Times(l, r):
return '(%s*%s)' % (l, r)
def _Divide(l, r):
return '(%s/%s)' % (l, r)
def _Value(x):
return x
try:
match(e, locals()) # visitor pattern
except NoMatchedError:
pass

Perhaps you want to define what match() does?
 
K

Kay Schluehr

BTW, Please don't ask "Why do you want to do like this"

No, I don't ask although it would be the interesting aspect for me ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top