Created
February 19, 2016 08:19
-
-
Save skyfe79/e2f6777fca53e324cd28 to your computer and use it in GitHub Desktop.
Functional BinarySearchTree 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
import Cocoa | |
indirect enum BST<T: Comparable> { | |
case Leaf | |
case Node(BST<T>, T, BST<T>) | |
} | |
var bst = BST.Node(.Leaf, 10, .Leaf) | |
extension BST { | |
init(_ value: T) { | |
self = .Node(.Leaf, value, .Leaf) | |
} | |
init() { | |
self = .Leaf | |
} | |
mutating func insert(x: T) { | |
switch self { | |
case .Leaf: | |
self = BST(x) | |
case .Node(var left, let v, var right): | |
if x < v { left.insert(x) } | |
if x > v { right.insert(x) } | |
self = .Node(left, v, right) | |
} | |
} | |
func contains(x: T) -> Bool { | |
switch self { | |
case .Leaf: | |
return false | |
case let .Node(_, y, _) where x == y: | |
return true | |
case let .Node(left, y, _) where x < y: | |
return left.contains(x) | |
case let .Node(_, y, right) where x > y: | |
return right.contains(x) | |
default: | |
return false | |
} | |
} | |
var count: Int { | |
switch self { | |
case .Leaf: | |
return 0 | |
case let .Node(left, _, right): | |
return left.count + 1 + right.count | |
} | |
} | |
var elements: [T] { | |
switch self { | |
case .Leaf: | |
return [] | |
case let .Node(left, x, right): | |
return left.elements + [x] + right.elements | |
} | |
} | |
var isEmpty: Bool { | |
switch self { | |
case .Leaf: | |
return true | |
default: | |
return false | |
} | |
} | |
var isBST: Bool { | |
switch self { | |
case .Leaf: | |
return true | |
case let .Node(left, x, right): | |
return left.elements.all { y in y < x } | |
&& right.elements.all { y in y > x } | |
&& left.isBST | |
&& right.isBST | |
} | |
} | |
} | |
extension Array { | |
func all<T> (predicate: (T) -> Bool) -> Bool { | |
for x in self { | |
let t = x as! T | |
if !predicate(t) { | |
return false | |
} | |
} | |
return true | |
} | |
} | |
bst.insert(20) | |
bst.insert(30) | |
bst.insert(1) | |
bst.contains(20) | |
bst.contains(102) | |
bst.elements | |
bst.count | |
bst.isEmpty | |
bst.isBST |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment