rosetree 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.py[oc]
3
+ build/
4
+ dist/
5
+ wheels/
6
+ *.egg-info
7
+ .venv
8
+ .coverage
9
+ TODO.*
rosetree-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025, Jeremy Silver
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,352 @@
1
+ Metadata-Version: 2.4
2
+ Name: rosetree
3
+ Version: 0.1.0
4
+ Summary: Generic tree data structure.
5
+ Project-URL: Documentation, https://github.com/jeremander/rosetree#readme
6
+ Project-URL: Issues, https://github.com/jeremander/rosetree/issues
7
+ Project-URL: Source, https://github.com/jeremander/rosetree
8
+ Author-email: Jeremy Silver <jeremys@nessiness.com>
9
+ License: MIT License
10
+
11
+ Copyright (c) 2025, Jeremy Silver
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Classifier: Programming Language :: Python
32
+ Requires-Python: >=3.9
33
+ Requires-Dist: typing-extensions>=4.10
34
+ Provides-Extra: draw
35
+ Requires-Dist: matplotlib; extra == 'draw'
36
+ Requires-Dist: networkx; extra == 'draw'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # rosetree
40
+
41
+ [![PyPI - Version](https://img.shields.io/pypi/v/rosetree)](https://pypi.org/project/rosetree/)
42
+ ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/jeremander/rosetree/workflow.yml)
43
+ ![Coverage Status](https://github.com/jeremander/rosetree/raw/coverage-badge/coverage-badge.svg)
44
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://raw.githubusercontent.com/jeremander/rosetree/refs/heads/main/LICENSE)
45
+ [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit)
46
+
47
+ ## Installation
48
+
49
+ `pip install rosetree`
50
+
51
+ Or, to ensure you have all the required dependencies for tree drawing:
52
+
53
+ `pip install rosetree[draw]`
54
+
55
+ ## Basics
56
+
57
+ `rosetree` provides a generic *multi-way tree* ("rose tree") data structure. It is inspired by Haskell's [Data.Tree](https://hackage-content.haskell.org/package/containers-0.8/docs/Data-Tree.html) library and is well suited to programming in a *functional* style.
58
+
59
+ We'll proceed by way of examples. First, let's create a simple `Tree` with integer node labels:
60
+
61
+ ```python
62
+ from rosetree import Tree
63
+
64
+ # build the tree
65
+ >>> tree = Tree(1, [Tree(2, [Tree(3), Tree(4)]), Tree(5)])
66
+
67
+ # draw the tree
68
+ >>> print(tree.pretty())
69
+ 1
70
+ ┌─┴──┐
71
+ 2 5
72
+ ┌┴─┐
73
+ 3 4
74
+ ```
75
+
76
+ We construct a `Tree` by specifying its root node and a list of child subtrees. A leaf node is therefore represented simply by a `Tree` with a node and no children.
77
+
78
+ ### Drawing
79
+
80
+ The `pretty` method of a `Tree` produces an "ASCII art" string that can be used to view the tree's structure. There are three styles you can choose from by providing a `style` argument to `pretty`:
81
+
82
+ ```python
83
+ # (this is the default style)
84
+ >>> print(tree.pretty(style='top-down'))
85
+ 1
86
+ ┌─┴──┐
87
+ 2 5
88
+ ┌┴─┐
89
+ 3 4
90
+
91
+ >>> print(tree.pretty(style='bottom-up'))
92
+ 1
93
+ ┌─┴──┐
94
+ 2 │
95
+ ┌┴─┐ │
96
+ 3 4 5
97
+
98
+ >>> print(tree.pretty(style='long'))
99
+ 1
100
+ ├── 2
101
+ │ ├── 3
102
+ │ └── 4
103
+ └── 5
104
+ ```
105
+
106
+ Alternatively you can create an image representation of the tree (this requires `matplotlib`):
107
+
108
+ ```python
109
+ # pop up a GUI window
110
+ >>> tree.draw()
111
+
112
+ # or just save a file directly
113
+ >>> tree.draw('my_tree.png')
114
+ ```
115
+
116
+ <img src="doc/tree.png" width="180" alt="Picture of a Tree produced by Tree.draw"/>
117
+
118
+ You may also provide a `draw_options` argument to customize some aspects of the tree drawing such as node color, edge color, text font, spacing, etc.
119
+
120
+ ### Accessing elements and properties
121
+
122
+ A `Tree` is actually implemented as a simple Python list of its child subtrees, plus an additional `node` attribute to access the top-level node:
123
+
124
+ ```python
125
+ # this is the root node
126
+ >>> tree.node
127
+ 1
128
+
129
+ # this is the left-most child subtree
130
+ >>> tree[0]
131
+ Tree(2, [Tree(3, []), Tree(4, [])])
132
+
133
+ # this is the right subtree of the left subtree
134
+ >>> tree[0][1]
135
+ Tree(4, [])
136
+
137
+ # this is the node at that subtree
138
+ >>> tree[0][1].node
139
+ 4
140
+
141
+ # this is the number of child subtrees of the root node
142
+ >>> len(tree)
143
+ 2
144
+ ```
145
+
146
+ A few other `Tree` methods can be used to calculate properties of the tree:
147
+
148
+ ```python
149
+ # total number of nodes in the tree
150
+ # NOTE: this is *not* the same as len(tree)!
151
+ >>> tree.size
152
+ 5
153
+
154
+ # maximum distance from the root to any leaf
155
+ >>> tree.height
156
+ 2
157
+ ```
158
+
159
+ You can iterate over nodes, leaves, or subtrees:
160
+
161
+ ```python
162
+ # iterate nodes with "pre-order" traversal (parents before children)
163
+ >>> list(tree.iter_nodes())
164
+ [1, 2, 3, 4, 5]
165
+
166
+ # iterate nodes with "post-order" traversal (children before parents)
167
+ >>> list(tree.iter_nodes(preorder=False))
168
+ [3, 4, 2, 5, 1]
169
+
170
+ # iterate leaves in left-to-right order
171
+ >>> list(tree.iter_leaves())
172
+ [3, 4, 5]
173
+
174
+ # iterate all subtrees with pre-order traversal
175
+ >>> list(tree.iter_subtrees())
176
+ [Tree(1, [Tree(2, [Tree(3, []), Tree(4, [])]), Tree(5, [])]),
177
+ Tree(2, [Tree(3, []), Tree(4, [])]),
178
+ Tree(3, []),
179
+ Tree(4, []),
180
+ Tree(5, [])]
181
+ ```
182
+
183
+ Note: all of these `iter_` methods produce a *lazy* generator to avoid storing all the items in memory. You can step through the generator with a for loop, or generate all the elements by calling `list`, as in the examples above.
184
+
185
+ For convenience, you can call `tree.leaves` to get a list of all the leaf nodes.
186
+
187
+ ### Inserting and deleting elements
188
+
189
+ A `Tree`, being a Python `list`, is capable of inserting or deleting elements fairly easily.
190
+
191
+ ```python
192
+ from copy import deepcopy
193
+
194
+ # make a copy of the tree, since we'll be modifying it
195
+ >>> tree_copy = deepcopy(tree)
196
+ >>> print(tree_copy.pretty())
197
+ 1
198
+ ┌─┴──┐
199
+ 2 5
200
+ ┌┴─┐
201
+ 3 4
202
+
203
+ # insert another child node below the root
204
+ >>> tree_copy.insert(1, Tree(6))
205
+ >>> print(tree_copy.pretty())
206
+ 1
207
+ ┌───┴┬──┐
208
+ 2 6 5
209
+ ┌┴─┐
210
+ 3 4
211
+
212
+ # delete node 4
213
+ >>> del tree_copy[0][1]
214
+ >>> print(tree_copy.pretty())
215
+ 1
216
+ ┌──┼──┐
217
+ 2 6 5
218
+
219
+ 3
220
+ ```
221
+
222
+ Note: Python lists are not optimized for insertion/deletion performance, so you should use this approach sparingly. It is better to build your tree structure up-front and change it as little as possible.
223
+
224
+ ### Functional tree operations
225
+
226
+ `Tree` exposes a variety of operations from functional programming, which allow you to manipulate trees in a consistent way regardless of the kind of data they contain. We'll go through a few examples.
227
+
228
+ #### **Map**: apply a function element-wise
229
+
230
+ The `map` method takes a function and applies it to each element of the tree, preserving the tree structure.
231
+
232
+ ```python
233
+ def square(x):
234
+ """Take the square of a number."""
235
+ return x ** 2
236
+
237
+ # square the value of each node
238
+ >>> tree_squared = tree.map(square)
239
+ >>> print(tree_squared.pretty())
240
+ 1
241
+ ┌──┴──┐
242
+ 4 25
243
+ ┌┴─┐
244
+ 9 16
245
+
246
+ # equivalently, as shorthand we can use a lambda expression
247
+ >>> tree.map(lambda x: x ** 2) == tree_squared
248
+ True
249
+ ```
250
+
251
+ For convenience there is also a `leaf_map` method, which applies the function only to leaf nodes, and an `internal_map` method, which applies the function only to internal (non-leaf) nodes.
252
+
253
+ ```python
254
+ >>> print(tree.leaf_map(square).pretty())
255
+ 1
256
+ ┌──┴──┐
257
+ 2 25
258
+ ┌┴─┐
259
+ 9 16
260
+
261
+ >>> print(tree.internal_map(square).pretty())
262
+ 1
263
+ ┌─┴──┐
264
+ 4 5
265
+ ┌┴─┐
266
+ 3 4
267
+ ```
268
+
269
+ #### **Reduce**: combine all nodes together
270
+
271
+ The `reduce` method takes a function with two arguments used to combine two values into a single value. It recursively applies the operation to combine all nodes into one value.
272
+
273
+ The input function should take two values of the same type and return a value of that type. The function does not have to be associative or commutative, but `reduce` will be more "well-behaved" if it is (i.e. the result will not depend as much on the structure/order of the nodes).
274
+
275
+ ```python
276
+ from operator import add, mul
277
+
278
+ # add all the nodes together
279
+ >>> tree.reduce(add)
280
+ 15
281
+
282
+ # multiply all the nodes together
283
+ >>> tree.reduce(mul)
284
+ 120
285
+
286
+ # concatenate all the nodes together (as strings)
287
+ # NOTE: this operation is associative but *not* commutative, so order matters
288
+ >>> tree.map(str).reduce(add)
289
+ '12345'
290
+ ```
291
+
292
+ #### **Scan**: partial reduce over each subtree
293
+
294
+ The `scan` method performs an operation which replaces each node in the tree with the result of running `reduce` with some function over that node's subtree. In effect this creates a tree of "partial" reductions.
295
+
296
+ For instance, if the provided function is `add`, this will produce the tree of "partial sums."
297
+
298
+ ```python
299
+ from operator import add
300
+
301
+ # original tree
302
+ >>> print(tree.pretty())
303
+ 1
304
+ ┌─┴──┐
305
+ 2 5
306
+ ┌┴─┐
307
+ 3 4
308
+
309
+ # tree of partial sums
310
+ >>> print(tree.scan(add).pretty())
311
+ 15
312
+ ┌─┴──┐
313
+ 9 5
314
+ ┌┴─┐
315
+ 3 4
316
+ ```
317
+
318
+ #### **Fold**: general purpose bottom-up recursion
319
+
320
+ The `fold` method is a general purpose construct for performing bottom-up recursion on a tree. The input is a function `f` taking two arguments, a parent node and a list of already-processed children. Starting at the root node, `tree.fold(f)` does the following:
321
+
322
+ 1. Recursively call `subtree.fold(f)` on each of the child subtrees.
323
+ 2. Return the result of `f(parent_node, processed_subtrees)`.
324
+
325
+ In functional programming this is also known as a *tree catamorphism*. It captures the pattern of building some value from the bottom of the tree upward. This means that nodes can pass information up to their ancestors, but not vice versa.
326
+
327
+ Fold is in fact a generalization of all the previous patterns discussed in this section; you can actually express `map`, `reduce`, and `scan` all in terms of `fold`!
328
+
329
+ Here is an example of using `fold` to modify a tree so that each node is converted to a pair `(node, num_descendants)`, where `node` is the original node's value, and `num_descendants` is the total number of descendants of that node.
330
+
331
+ ```python
332
+ def f(node, children):
333
+ # add the number of children to the total number of childrens' descendants
334
+ num_descendants = len(children) + sum(child.node[1] for child in children)
335
+ # return a new tree whose root node includes the number of descendants
336
+ return Tree((node, num_descendants), children)
337
+
338
+ >>> tree_with_descendants = tree.fold(f)
339
+
340
+ >>> print(tree_with_descendants.pretty())
341
+ (1, 4)
342
+ ┌─────┴─────┐
343
+ (2, 2) (5, 0)
344
+ ┌───┴───┐
345
+ (3, 0) (4, 0)
346
+ ```
347
+
348
+ ## License
349
+
350
+ This library is open-source and licensed under the [MIT License](LICENSE).
351
+
352
+ Contributions are welcome!
@@ -0,0 +1,314 @@
1
+ # rosetree
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/rosetree)](https://pypi.org/project/rosetree/)
4
+ ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/jeremander/rosetree/workflow.yml)
5
+ ![Coverage Status](https://github.com/jeremander/rosetree/raw/coverage-badge/coverage-badge.svg)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://raw.githubusercontent.com/jeremander/rosetree/refs/heads/main/LICENSE)
7
+ [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit)
8
+
9
+ ## Installation
10
+
11
+ `pip install rosetree`
12
+
13
+ Or, to ensure you have all the required dependencies for tree drawing:
14
+
15
+ `pip install rosetree[draw]`
16
+
17
+ ## Basics
18
+
19
+ `rosetree` provides a generic *multi-way tree* ("rose tree") data structure. It is inspired by Haskell's [Data.Tree](https://hackage-content.haskell.org/package/containers-0.8/docs/Data-Tree.html) library and is well suited to programming in a *functional* style.
20
+
21
+ We'll proceed by way of examples. First, let's create a simple `Tree` with integer node labels:
22
+
23
+ ```python
24
+ from rosetree import Tree
25
+
26
+ # build the tree
27
+ >>> tree = Tree(1, [Tree(2, [Tree(3), Tree(4)]), Tree(5)])
28
+
29
+ # draw the tree
30
+ >>> print(tree.pretty())
31
+ 1
32
+ ┌─┴──┐
33
+ 2 5
34
+ ┌┴─┐
35
+ 3 4
36
+ ```
37
+
38
+ We construct a `Tree` by specifying its root node and a list of child subtrees. A leaf node is therefore represented simply by a `Tree` with a node and no children.
39
+
40
+ ### Drawing
41
+
42
+ The `pretty` method of a `Tree` produces an "ASCII art" string that can be used to view the tree's structure. There are three styles you can choose from by providing a `style` argument to `pretty`:
43
+
44
+ ```python
45
+ # (this is the default style)
46
+ >>> print(tree.pretty(style='top-down'))
47
+ 1
48
+ ┌─┴──┐
49
+ 2 5
50
+ ┌┴─┐
51
+ 3 4
52
+
53
+ >>> print(tree.pretty(style='bottom-up'))
54
+ 1
55
+ ┌─┴──┐
56
+ 2 │
57
+ ┌┴─┐ │
58
+ 3 4 5
59
+
60
+ >>> print(tree.pretty(style='long'))
61
+ 1
62
+ ├── 2
63
+ │ ├── 3
64
+ │ └── 4
65
+ └── 5
66
+ ```
67
+
68
+ Alternatively you can create an image representation of the tree (this requires `matplotlib`):
69
+
70
+ ```python
71
+ # pop up a GUI window
72
+ >>> tree.draw()
73
+
74
+ # or just save a file directly
75
+ >>> tree.draw('my_tree.png')
76
+ ```
77
+
78
+ <img src="doc/tree.png" width="180" alt="Picture of a Tree produced by Tree.draw"/>
79
+
80
+ You may also provide a `draw_options` argument to customize some aspects of the tree drawing such as node color, edge color, text font, spacing, etc.
81
+
82
+ ### Accessing elements and properties
83
+
84
+ A `Tree` is actually implemented as a simple Python list of its child subtrees, plus an additional `node` attribute to access the top-level node:
85
+
86
+ ```python
87
+ # this is the root node
88
+ >>> tree.node
89
+ 1
90
+
91
+ # this is the left-most child subtree
92
+ >>> tree[0]
93
+ Tree(2, [Tree(3, []), Tree(4, [])])
94
+
95
+ # this is the right subtree of the left subtree
96
+ >>> tree[0][1]
97
+ Tree(4, [])
98
+
99
+ # this is the node at that subtree
100
+ >>> tree[0][1].node
101
+ 4
102
+
103
+ # this is the number of child subtrees of the root node
104
+ >>> len(tree)
105
+ 2
106
+ ```
107
+
108
+ A few other `Tree` methods can be used to calculate properties of the tree:
109
+
110
+ ```python
111
+ # total number of nodes in the tree
112
+ # NOTE: this is *not* the same as len(tree)!
113
+ >>> tree.size
114
+ 5
115
+
116
+ # maximum distance from the root to any leaf
117
+ >>> tree.height
118
+ 2
119
+ ```
120
+
121
+ You can iterate over nodes, leaves, or subtrees:
122
+
123
+ ```python
124
+ # iterate nodes with "pre-order" traversal (parents before children)
125
+ >>> list(tree.iter_nodes())
126
+ [1, 2, 3, 4, 5]
127
+
128
+ # iterate nodes with "post-order" traversal (children before parents)
129
+ >>> list(tree.iter_nodes(preorder=False))
130
+ [3, 4, 2, 5, 1]
131
+
132
+ # iterate leaves in left-to-right order
133
+ >>> list(tree.iter_leaves())
134
+ [3, 4, 5]
135
+
136
+ # iterate all subtrees with pre-order traversal
137
+ >>> list(tree.iter_subtrees())
138
+ [Tree(1, [Tree(2, [Tree(3, []), Tree(4, [])]), Tree(5, [])]),
139
+ Tree(2, [Tree(3, []), Tree(4, [])]),
140
+ Tree(3, []),
141
+ Tree(4, []),
142
+ Tree(5, [])]
143
+ ```
144
+
145
+ Note: all of these `iter_` methods produce a *lazy* generator to avoid storing all the items in memory. You can step through the generator with a for loop, or generate all the elements by calling `list`, as in the examples above.
146
+
147
+ For convenience, you can call `tree.leaves` to get a list of all the leaf nodes.
148
+
149
+ ### Inserting and deleting elements
150
+
151
+ A `Tree`, being a Python `list`, is capable of inserting or deleting elements fairly easily.
152
+
153
+ ```python
154
+ from copy import deepcopy
155
+
156
+ # make a copy of the tree, since we'll be modifying it
157
+ >>> tree_copy = deepcopy(tree)
158
+ >>> print(tree_copy.pretty())
159
+ 1
160
+ ┌─┴──┐
161
+ 2 5
162
+ ┌┴─┐
163
+ 3 4
164
+
165
+ # insert another child node below the root
166
+ >>> tree_copy.insert(1, Tree(6))
167
+ >>> print(tree_copy.pretty())
168
+ 1
169
+ ┌───┴┬──┐
170
+ 2 6 5
171
+ ┌┴─┐
172
+ 3 4
173
+
174
+ # delete node 4
175
+ >>> del tree_copy[0][1]
176
+ >>> print(tree_copy.pretty())
177
+ 1
178
+ ┌──┼──┐
179
+ 2 6 5
180
+
181
+ 3
182
+ ```
183
+
184
+ Note: Python lists are not optimized for insertion/deletion performance, so you should use this approach sparingly. It is better to build your tree structure up-front and change it as little as possible.
185
+
186
+ ### Functional tree operations
187
+
188
+ `Tree` exposes a variety of operations from functional programming, which allow you to manipulate trees in a consistent way regardless of the kind of data they contain. We'll go through a few examples.
189
+
190
+ #### **Map**: apply a function element-wise
191
+
192
+ The `map` method takes a function and applies it to each element of the tree, preserving the tree structure.
193
+
194
+ ```python
195
+ def square(x):
196
+ """Take the square of a number."""
197
+ return x ** 2
198
+
199
+ # square the value of each node
200
+ >>> tree_squared = tree.map(square)
201
+ >>> print(tree_squared.pretty())
202
+ 1
203
+ ┌──┴──┐
204
+ 4 25
205
+ ┌┴─┐
206
+ 9 16
207
+
208
+ # equivalently, as shorthand we can use a lambda expression
209
+ >>> tree.map(lambda x: x ** 2) == tree_squared
210
+ True
211
+ ```
212
+
213
+ For convenience there is also a `leaf_map` method, which applies the function only to leaf nodes, and an `internal_map` method, which applies the function only to internal (non-leaf) nodes.
214
+
215
+ ```python
216
+ >>> print(tree.leaf_map(square).pretty())
217
+ 1
218
+ ┌──┴──┐
219
+ 2 25
220
+ ┌┴─┐
221
+ 9 16
222
+
223
+ >>> print(tree.internal_map(square).pretty())
224
+ 1
225
+ ┌─┴──┐
226
+ 4 5
227
+ ┌┴─┐
228
+ 3 4
229
+ ```
230
+
231
+ #### **Reduce**: combine all nodes together
232
+
233
+ The `reduce` method takes a function with two arguments used to combine two values into a single value. It recursively applies the operation to combine all nodes into one value.
234
+
235
+ The input function should take two values of the same type and return a value of that type. The function does not have to be associative or commutative, but `reduce` will be more "well-behaved" if it is (i.e. the result will not depend as much on the structure/order of the nodes).
236
+
237
+ ```python
238
+ from operator import add, mul
239
+
240
+ # add all the nodes together
241
+ >>> tree.reduce(add)
242
+ 15
243
+
244
+ # multiply all the nodes together
245
+ >>> tree.reduce(mul)
246
+ 120
247
+
248
+ # concatenate all the nodes together (as strings)
249
+ # NOTE: this operation is associative but *not* commutative, so order matters
250
+ >>> tree.map(str).reduce(add)
251
+ '12345'
252
+ ```
253
+
254
+ #### **Scan**: partial reduce over each subtree
255
+
256
+ The `scan` method performs an operation which replaces each node in the tree with the result of running `reduce` with some function over that node's subtree. In effect this creates a tree of "partial" reductions.
257
+
258
+ For instance, if the provided function is `add`, this will produce the tree of "partial sums."
259
+
260
+ ```python
261
+ from operator import add
262
+
263
+ # original tree
264
+ >>> print(tree.pretty())
265
+ 1
266
+ ┌─┴──┐
267
+ 2 5
268
+ ┌┴─┐
269
+ 3 4
270
+
271
+ # tree of partial sums
272
+ >>> print(tree.scan(add).pretty())
273
+ 15
274
+ ┌─┴──┐
275
+ 9 5
276
+ ┌┴─┐
277
+ 3 4
278
+ ```
279
+
280
+ #### **Fold**: general purpose bottom-up recursion
281
+
282
+ The `fold` method is a general purpose construct for performing bottom-up recursion on a tree. The input is a function `f` taking two arguments, a parent node and a list of already-processed children. Starting at the root node, `tree.fold(f)` does the following:
283
+
284
+ 1. Recursively call `subtree.fold(f)` on each of the child subtrees.
285
+ 2. Return the result of `f(parent_node, processed_subtrees)`.
286
+
287
+ In functional programming this is also known as a *tree catamorphism*. It captures the pattern of building some value from the bottom of the tree upward. This means that nodes can pass information up to their ancestors, but not vice versa.
288
+
289
+ Fold is in fact a generalization of all the previous patterns discussed in this section; you can actually express `map`, `reduce`, and `scan` all in terms of `fold`!
290
+
291
+ Here is an example of using `fold` to modify a tree so that each node is converted to a pair `(node, num_descendants)`, where `node` is the original node's value, and `num_descendants` is the total number of descendants of that node.
292
+
293
+ ```python
294
+ def f(node, children):
295
+ # add the number of children to the total number of childrens' descendants
296
+ num_descendants = len(children) + sum(child.node[1] for child in children)
297
+ # return a new tree whose root node includes the number of descendants
298
+ return Tree((node, num_descendants), children)
299
+
300
+ >>> tree_with_descendants = tree.fold(f)
301
+
302
+ >>> print(tree_with_descendants.pretty())
303
+ (1, 4)
304
+ ┌─────┴─────┐
305
+ (2, 2) (5, 0)
306
+ ┌───┴───┐
307
+ (3, 0) (4, 0)
308
+ ```
309
+
310
+ ## License
311
+
312
+ This library is open-source and licensed under the [MIT License](LICENSE).
313
+
314
+ Contributions are welcome!