Binary trees in F#: functional polymorphism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type BinaryTree = | |
|Node of obj * BinaryTree * BinaryTree | |
|Empty | |
member tree.Traverse f = | |
match tree with | |
|Node(data, l, r) -> | |
f data | |
l.Traverse f | |
r.Traverse f | |
|Empty -> () | |
let tree = Node("Node 1", Node("Node 2", Empty, Empty), Empty) | |
tree.Traverse (printfn "%A") | |
> | |
"Node 1" | |
"Node 2" |
That's it. Having no class hierarchy with its usual noisy methods overriding and so on, we've got polymorphism - succinct and highly readable. Wow!
Comments