Binary trees in F#: functional polymorphism

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"
view raw gistfile1.fs hosted with ❤ by GitHub

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

Popular posts from this blog

Regular expressions: Rust vs F# vs Scala

Hash maps: Rust, F#, D, Go, Scala

Haskell: performance