Skip to content

Instantly share code, notes, and snippets.

@thexande
Created January 31, 2020 19:08
Show Gist options
  • Save thexande/bb5bbda6d183e4415fc51501534e5f8e to your computer and use it in GitHub Desktop.
Save thexande/bb5bbda6d183e4415fc51501534e5f8e to your computer and use it in GitHub Desktop.
enum Node<T> where T: Equatable & Comparable {
case empty
indirect case value(left: Node<T>, value: T, right: Node<T>)
}
extension Node {
func isValid(within range: ClosedRange<T>) -> Bool {
switch self {
case .empty:
return true
case let .value(left, value, right):
guard range.contains(value) else { return false }
return left.isValid(within: range.lowerBound...value)
&& right.isValid(within: value...range.upperBound)
}
}
}
let tree = Node<Int>.value(left: .value(left: .empty,
value: 10,
right: .empty),
value: 12,
right: .empty)
print(tree.isValid(within: Int.min...Int.max)) // => true
// Given that emoji are just unicode under the hood,
// they are sequential and can therefore be used to
// create a closed countable range :joy:
let emojiTree = Node<Character>.value(left: .value(left: .empty,
value: "😅",
right: .empty),
value: "😎",
right: .empty)
print(emojiTree.isValid(within: "😀"..."🥳")) // => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment