Rudimentary demo of binary search tree using inheritance.
Chris Pressey
2 years ago
0 | # Rudiments of a BST using inheritance in Nim | |
1 | # TODO: write a version using Object Variants instead, to compare | |
2 | ||
3 | type Tree = ref object of RootObj | |
4 | value: int | |
5 | ||
6 | type Branch = ref object of Tree | |
7 | left: Tree | |
8 | right: Tree | |
9 | ||
10 | type Leaf = ref object of Tree | |
11 | ||
12 | method minValue(self: Tree): int {.base.} = | |
13 | return self.value | |
14 | method minValue(self: Branch): int = | |
15 | if self.left == nil: | |
16 | return self.value | |
17 | else: | |
18 | return minValue(self.left) | |
19 | method minValue(self: Leaf): int = | |
20 | return self.value | |
21 | ||
22 | var z: Tree | |
23 | ||
24 | z = Branch(value: 4, left: Leaf(value: 2), right: Leaf(value: 9)) | |
25 | echo minValue(z) | |
26 | ||
27 | z = Branch(value: 4, left: nil, right: nil) | |
28 | echo minValue(z) |