-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.comp
More file actions
67 lines (49 loc) · 1.58 KB
/
tree.comp
File metadata and controls
67 lines (49 loc) · 1.58 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
Binary search tree
Operations for a minimal binary tree with shape-dispatched
insertion, lookup, and in-order traversal.
Highlights
- Immutable trees share unchanged nodes across generations, inserting a value only rebuilds the path from root to insertion point
- `@flat` wrapper on `tree-values` concatenates multiple expressions into a single sequence, the in-order traversal reads as three lines: left, self, right
- `~nil` vs `~tree` overloads replace null checks, the base case and recursive case are separate function definitions, not branches in one function
- `@update` on `tree-insert ~tree` means the body only returns the one child field that changed, the other child and value pass through
*/
!shape tree ~{value~num left~branch right~branch}
!shape branch ~(tree | nil) = nil
!main console [
{5 3 8 1 7 9}
| reduce initial=nil tree-insert
| tree-values
| output
]
/// Add new value into tree, dispatched on nil vs tree
!pure empty.tree-insert ~nil [
!param value ~num
{value} | tree
]
!pure tree-insert ~tree @update(
!param value ~num
!on value <> $.value
~less {left = [$.left | tree-insert value]}
~any {right = [$.right | tree-insert value]}
)
/// Check if tree contains value
!pure empty.tree-contains ~nil (
!param value ~num
false
)
!pure tree-contains ~tree (
!param value ~num
!on value <> $.value
~less [$.left | tree-contains value]
~greater [$.right | tree-contains value]
~equal true
)
/// Iterate values from tree in order
!pure empty.tree-values ~nil {
}
!pure tree-values ~tree @flat {
[$.left | tree-values]
{$.value}
[$.right | tree-values]
}