Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AlexanderBollbach/842ba7de20f5d203148600fa365bea08 to your computer and use it in GitHub Desktop.
Save AlexanderBollbach/842ba7de20f5d203148600fa365bea08 to your computer and use it in GitHub Desktop.
//
//NonEmpty
//DataSiteOne
//
//Created by Huang, Eric on 4/12/18
//Copyright © 2018 Merrill Corporation. All rights reserved.
import Foundation
public protocol NonEmpty {
associatedtype Collection: Swift.Collection
var head: Collection.Iterator.Element { get }
var tail: Collection { get }
}
extension NonEmpty {
var count: Int {
return tail.count.advanced(by: 1)
}
public var first: Collection.Iterator.Element {
return self.head
}
}
extension NonEmpty where Collection: RandomAccessCollection {
public var last: Collection.Iterator.Element {
return self.tail.last ?? self.head
}
}
struct NonEmptySet<Element>: NonEmpty where Element: Hashable {
let head: Element
let tail: Set<Element>
}
extension NonEmptySet {
init(_ head: Element, _ tail: Element...) {
self.init(head: head, tail: Set(tail).subtracting([head]))
}
init(_ head: Element) {
self.init(head: head, tail: Set())
}
}
func == <T>(lhs: NonEmptySet<T>, rhs: NonEmptySet<T>) -> Bool {
return lhs.head == rhs.head && lhs.tail == rhs.tail
}
func != <T>(lhs: NonEmptySet<T>, rhs: NonEmptySet<T>) -> Bool {
return lhs.head != rhs.head || lhs.tail != rhs.tail
}
infix operator +|: AdditionPrecedence
precedencegroup AdditionPrecedence {
associativity: left
}
func +| <T>(head: T, tail: Set<T>) -> NonEmptySet<T> {
return NonEmptySet<T>(head: head, tail: tail.subtracting([head]))
}
extension Array where Element: Hashable {
init(_ nonEmpty: NonEmptySet<Element>) {
self = [nonEmpty.head] + Array(nonEmpty.tail)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment