Skip to content

Tree

funstruct.collections.tree

Immutable binary tree.

Tree[A] = Leaf(value) | Branch(value, left, right)

Every node holds a value. map applies a function to all values, preserving structure. Tree is a Functor but not a Monad.

Examples:

>>> from funstruct.collections.tree import Tree, Leaf, Branch
>>> from funstruct.collections.cons import Cons, Nil
>>> t = Branch(1, Leaf(2), Leaf(3))
>>> t.map(lambda x: x * 10)
Branch(10, Leaf(20), Leaf(30))
>>> t.size
3
>>> t.depth
1
>>> big = Branch(1, Branch(2, Leaf(3), Leaf(4)), Leaf(5))
>>> big.map(str)
Branch('1', Branch('2', Leaf('3'), Leaf('4')), Leaf('5'))
>>> big.to_list()
Cons(3, Cons(2, Cons(4, Cons(1, Cons(5, Nil())))))
>>> big.depth
2

fold — reduce the tree:

>>> t.fold(lambda v: v, lambda v, l, r: v + l + r)
6

Tree

Bases: DataType, Generic[A]

Binary tree where every node holds a value.

Source code in funstruct/collections/tree/__init__.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Tree(DataType, Generic[A]):
    """Binary tree where every node holds a value."""

    @property
    @abstractmethod
    def size(self) -> int: ...

    @property
    @abstractmethod
    def depth(self) -> int: ...

    @abstractmethod
    def fold(
        self,
        on_leaf: Callable[[A], C],
        on_branch: Callable[[A, C, C], C],
    ) -> C: ...

    @abstractmethod
    def to_list(self) -> CList[A]: ...

    @abstractmethod
    def fold_right(self, acc: B, f: Callable[[A, B], B]) -> B: ...

    def fold_left(self, acc: B, f: Callable[[B, A], B]) -> B:
        items: list = []
        self.fold_right(None, lambda a, _: items.append(a))
        for item in items:
            acc = f(acc, item)
        return acc

    def length(self) -> int:
        return self.fold_right(0, lambda _, acc: acc + 1)

    def is_empty(self) -> bool:
        return False

    @abstractmethod
    def traverse(self, f: Callable, pure_fn: Callable) -> object: ...

    def sequence(self, pure_fn: Callable) -> object:
        return self.traverse(lambda x: x, pure_fn)

Leaf dataclass

Bases: Tree[A]

Terminal node holding a single value.

Source code in funstruct/collections/tree/__init__.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
@dataclass(frozen=True, eq=False)
class Leaf(Tree[A]):
    """Terminal node holding a single value."""

    value: A

    @property
    def size(self) -> int:
        return 1

    @property
    def depth(self) -> int:
        return 0

    def fold(
        self,
        on_leaf: Callable[[A], C],
        on_branch: Callable[[A, C, C], C],
    ) -> C:
        return on_leaf(self.value)

    def fold_right(self, acc: B, f: Callable[[A, B], B]) -> B:
        return f(self.value, acc)

    def traverse(self, f: Callable, pure_fn: Callable) -> object:
        return f(self.value).map(Leaf)

    def to_list(self) -> CList[A]:
        return Cons.pure(self.value)

    def __eq__(self, other: object) -> bool:
        match other:
            case Leaf(v):
                return self.value == v
            case _:
                return False

    def __repr__(self) -> str:
        return f"Leaf({repr(self.value)})"

Branch dataclass

Bases: Tree[A]

Internal node with a value and two children.

Source code in funstruct/collections/tree/__init__.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
@dataclass(frozen=True, eq=False)
class Branch(Tree[A]):
    """Internal node with a value and two children."""

    value: A
    left: Tree[A]
    right: Tree[A]

    @property
    def size(self) -> int:
        return 1 + self.left.size + self.right.size

    @property
    def depth(self) -> int:
        return 1 + max(self.left.depth, self.right.depth)

    def fold(
        self,
        on_leaf: Callable[[A], C],
        on_branch: Callable[[A, C, C], C],
    ) -> C:
        return on_branch(
            self.value,
            self.left.fold(on_leaf, on_branch),
            self.right.fold(on_leaf, on_branch),
        )

    def fold_right(self, acc: B, f: Callable[[A, B], B]) -> B:
        acc = self.right.fold_right(acc, f)
        acc = f(self.value, acc)
        acc = self.left.fold_right(acc, f)
        return acc

    def traverse(self, f: Callable, pure_fn: Callable) -> object:
        fv = f(self.value)
        fl = self.left.traverse(f, pure_fn)
        fr = self.right.traverse(f, pure_fn)
        return (
            pure_fn(lambda v: lambda l: lambda r: Branch(v, l, r)).ap(fv).ap(fl).ap(fr)
        )

    def to_list(self) -> CList[A]:
        return self.left.to_list() + Cons(self.value, self.right.to_list())

    def __eq__(self, other: object) -> bool:
        match other:
            case Branch(v, l, r):
                return self.value == v and self.left == l and self.right == r
            case _:
                return False

    def __repr__(self) -> str:
        return f"Branch({repr(self.value)}, {repr(self.left)}, {repr(self.right)})"