Skip to content

Instantly share code, notes, and snippets.

@HenningBrandt
Created February 11, 2015 04:44
Show Gist options
  • Save HenningBrandt/07f497474b3f2f6d83f4 to your computer and use it in GitHub Desktop.
Save HenningBrandt/07f497474b3f2f6d83f4 to your computer and use it in GitHub Desktop.
Recursive, generic enums in Swift
protocol TreeLike {}
enum Tree<T> : TreeLike {
case Leaf(@autoclosure () -> T)
case Node(TreeLike, TreeLike)
}
func node<T>(left: Tree<T>, right: Tree<T>) -> Tree<T> {
return Tree.Node(left, right)
}
let tree : Tree<Int> = node(node(.Leaf(2), .Leaf(3)), node(.Leaf(5), .Leaf(7)))
func searchInTree<T: Equatable>(search: T, tree: Tree<T>) -> Bool {
switch tree {
case .Leaf(let x):
return x() == search
case .Node(let l as Tree<T>, let r as Tree<T>):
return searchInTree(search, l) || searchInTree(search, r)
default:
return false
}
}
searchInTree(7, tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment