Skip to content

Instantly share code, notes, and snippets.

@rbarbera
Last active October 31, 2018 16:00
Show Gist options
  • Save rbarbera/44b60b6c3622eb8a9c4de6b06f27f2ef to your computer and use it in GitHub Desktop.
Save rbarbera/44b60b6c3622eb8a9c4de6b06f27f2ef to your computer and use it in GitHub Desktop.
Algebraic Binary tree implementation in Swift
import Foundation
indirect enum Tree<T> {
case empty
case node(_ value: T, _ left: Tree<T>, _ right: Tree<T>)
}
extension Tree: CustomStringConvertible where T: CustomStringConvertible {
var description: String {
switch self {
case .empty:
return "empty"
case let .node(v, left, right):
return "node(\(v), \(left.description), \(right.description))"
}
}
}
let tree = Tree.node(42,
.node(0, .empty, .empty),
.empty)
print(tree) // node(42, node(0, empty, empty), empty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment