Created
February 11, 2015 04:44
-
-
Save HenningBrandt/07f497474b3f2f6d83f4 to your computer and use it in GitHub Desktop.
Recursive, generic enums in Swift
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
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