Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active July 1, 2016 00:05
Show Gist options
  • Save pauljohanneskraft/bbc8ac65799c3052261571e653f912b1 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/bbc8ac65799c3052261571e653f912b1 to your computer and use it in GitHub Desktop.
Mathematical logical quantifiers implemented in Swift

Quantifiers

let b = [0,1,2]   { $0 <= 1 } // true
let c = [0,1,2]   { $0 < 10 } // true
let d = [0,1,2] ∃! { $0 == 1 } // true

Mathematical logical operators, like the universal (∀) and the existential (∃) quantifier, as well as ∃! meaning "exactly one exists".

mathematically correct would be
∃ x ∈ [0,1,2]: x <= 1
∀ x ∈ [0,1,2]: x < 10
∃!x ∈ [0,1,2]: x == 1

See https://en.wikipedia.org/wiki/Quantifier_(logic)

infix operator ∀ {}
infix operator ∃ {}
infix operator ∃! {}
func ∀<C: Collection where C.IndexDistance == Int>(set: C, _ predicate: (C.Iterator.Element) throws -> Bool) rethrows -> Bool {
return try set.count == set.filter(predicate).count
}
func ∃<C: Collection>(set: C, _ predicate: (C.Iterator.Element) throws -> Bool) rethrows -> Bool {
return try set.contains(predicate)
}
func ∃!<C: Collection>(set: C, _ predicate: (C.Iterator.Element) throws -> Bool) rethrows -> Bool {
return try set.filter(predicate).count == 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment