Sunday, 11 December 2016

Python Immutable Trees

When I was building immutable python lists interface, I realized, than in the same way an immutable binary tree (or ternary and other) can be created - using python Abstract Base Class. Code looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Nil_tree:
    """class Nil_tree, the empty tree"""
    
    def is_empty(self):
        return True
    def left(self):
        return Exception("Empty")
    def right(self):
        return Exception("Empty")
    def __str__(self):
        return "()"
    
class Binary_tree:
    """Class Binary_tree, the non empty tree: ( val, left, right)"""
            
    def __init__(self, _item, _left, _right):
        self.item = _item
        self.left = _left
        self.right = _right
        
    def is_empty(self):
        return False


        
class Tree(metaclass=ABCMeta):
    
    @abstractmethod
    def is_empty():
        pass
    def item():
        pass
    def left():
        pass
    def right():
        pass
    
List.register(Nil_tree);
List.register(Binary_tree)

I would call it purely functional, can it be used in practice?  Maybe to do some functional stuff in python. This code plus some basic tree functions freely available on github.
PS I, also added lots of methods to cons lists, code here.

No comments: