Think about how you'd implement them in a more principled way. You could
use any of the version 1 -- version 5 implementation of lists as a model.
- To keep things simple, I recommend starting with the version 3 pattern. And
- stick to binary trees.
+ To keep things simple, we'll stick to binary trees. A node will either be a
+ *leaf* of the tree, or it will have exactly two children.
There are two kinds of trees to think about. In one sort of tree, it's only
- the tree's *leaves* that are labeled:
+ the tree's leaves that are labeled:
- +
+ .
/ \
- + 3
+ . 3
/ \
1 2
Linguists often use trees of this sort. The inner, non-leaf nodes of the
-tree have associated values. But what values they are can be determined from
+tree do have associated values. But what values they are can be determined from
the structure of the tree and the values of the node's left and right children.
So the inner node doesn't need its own independent label.
Similarly, the leaf-labeled tree:
- +
+ .
/ \
- + 3
+ . 3
/ \
1 2
can be thought of as a data structure of the form:
- Node (its_left_subtree, its_right_subtree) | Leaf (its_label)
+ Leaf (its_label) | Non_leaf (its_left_subtree, its_right_subtree)
and that could be implemented in v2 form as:
- the_tree (\left right. node_handler) (\label. lead_handler)
+ the_tree (\left right. non_leaf_handler) (\label. leaf_handler)
And the node-labeled tree:
can be thought of as a data structure of the form:
- Node (its_left_subtree, its_label, its_right_subtree) | Leaf
+ Leaf | Non_leaf (its_left_subtree, its_label, its_right_subtree)
and that could be implemented in v2 form as:
- the_tree (\left label right. node_handler) leaf_result
+ the_tree (\left label right. non_leaf_handler) leaf_result
What would correspond to "folding" a function `f` and base value `z` over a
the label of the root (topmost node) of a tree; extracting the left subtree of
a node; and so on.
- Think about different ways you might implement v3-style trees.
+ Think about different ways you might implement leaf-labeled trees.
If you had one tree and wanted to make a larger tree out of it, adding in a
new element, how would you do that?
you're building pretty "balanced" in this way?
This is a large topic in computer science. There's no need for you to learn
-any of the various strategies that they've developed for doing this. But
+the various strategies that they've developed for doing this. But
thinking in broad brush-strokes about what strategies might be promising will
help strengthen your understanding of trees, and useful ways to implement them
in a purely functional setting like the lambda calculus.