Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active July 1, 2016 00:11
Show Gist options
  • Save pauljohanneskraft/4f0195f48a27d93e51691870c8e38aca to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/4f0195f48a27d93e51691870c8e38aca to your computer and use it in GitHub Desktop.
Set operators

Collection operators

let isSubset = [0,1]  [0,1,2] // true
let intersection = [0,1]  [0,2] // [0]
let union = [0,1]  [0,2] // [0,1,2]
infix operator ⊂ {} // subset
func ⊂ <C : Collection where C.IndexDistance == Int, C.Iterator.Element: Equatable>(array1: C, array2: C) -> Bool {
guard array1.count <= array2.count else { return false }
let c = array1.filter({
(a: C.Iterator.Element) -> Bool in
return array2.contains({ $0 == a })
}).count
return c == array1.count
}
infix operator ⋃ {}
func ⋃ <T> (left: Set<T>, right: Set<T>) -> Set<T> {
return left.union(right)
}
infix operator ⋃= {}
func ⋃= <T> (left: inout Set<T>, right: Set<T>) {
left.formUnion(right)
}
infix operator ⋂ {}
func ⋂ <T>(left: Set<T>, right: Set<T>) -> Set<T> {
return left.intersection(right)
}
infix operator ⋂= {}
func ⋂= <T : Comparable>( left: inout Set<T>, right: Set<T>) {
left.formIntersection(right)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment