[ create a new paste ] login | about

Link: http://codepad.org/cYZ5SaBZ    [ raw code | output | fork ]

Python, pasted on Mar 10:
#!/usr/bin/python

class _AlgebraicDataType(object):
    def __init__(self, *args):
        if len(args) != len(self.d[1:]):
            raise ValueError
        self.v = args
    def __rshift__(self, s):
        L = s.split()
        if self.d[0] == L[0]:
            for name, value in zip(L[1:], self.v):
                globals()[name] = value
            return True
        else:
            return False

def deftype(name, definition):
    dss = [d.split() for d in definition.split("|")]
    basecls = type(name, (object,), {})
    globals()[name] = basecls
    for ds in dss:
        globals()[ds[0]] = type(ds[0], (basecls, _AlgebraicDataType), dict(d=ds))

deftype("Tree", "Empty | Leaf int | Node Tree Tree")

def depth(tree):
    if tree >> "Empty":
        return 0
    elif tree >> "Leaf n":
        return 1
    elif tree >> "Node l r":
        return 1 + max(depth(l), depth(r))

if __name__ == '__main__':
    print depth(Empty())
    print depth(Node(Node(Leaf(1), Leaf(2)), Leaf(3)))


Output:
1
2
0
3


Create a new paste based on this one


Comments: