Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
Created March 26, 2015 23:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JadenGeller/a818afd3733b942ae676 to your computer and use it in GitHub Desktop.
Save JadenGeller/a818afd3733b942ae676 to your computer and use it in GitHub Desktop.
Swift Inequality Interval
// Example
for x in 1...10 {
if 3 < x <= 8 {
println(x) // -> 4 -> 5 -> 6 -> 7 -> 8
}
}
// Implementation
enum ComparisonValue<T> : BooleanType {
case False
case True(T)
var boolValue: Bool {
get {
switch self {
case .False: return false
case .True: return true
}
}
}
}
infix operator < { associativity left }
infix operator <= { associativity left }
infix operator > { associativity left }
infix operator >= { associativity left }
// Note that left associativity means we store the rhs value
func <<T : Comparable>(lhs: T, rhs: T) -> ComparisonValue<T> {
let comparison: Bool = lhs < rhs
if comparison { return .True(rhs) }
else { return .False }
}
func <<T : Comparable>(lhs: ComparisonValue<T>, rhs: T) -> ComparisonValue<T> {
switch lhs {
case .True(let lhsValue): return lhsValue < rhs
case .False: return .False
}
}
func ><T : Comparable>(lhs: T, rhs: T) -> ComparisonValue<T> {
let comparison: Bool = lhs > rhs
if comparison { return .True(rhs) }
else { return .False }
}
func ><T : Comparable>(lhs: ComparisonValue<T>, rhs: T) -> ComparisonValue<T> {
switch lhs {
case .True(let lhsValue): return lhsValue > rhs
case .False: return .False
}
}
func >=<T : Comparable>(lhs: T, rhs: T) -> ComparisonValue<T> {
let comparison: Bool = lhs >= rhs
if comparison { return .True(rhs) }
else { return .False }
}
func >=<T : Comparable>(lhs: ComparisonValue<T>, rhs: T) -> ComparisonValue<T> {
switch lhs {
case .True(let lhsValue): return lhsValue >= rhs
case .False: return .False
}
}
func <=<T : Comparable>(lhs: T, rhs: T) -> ComparisonValue<T> {
let comparison: Bool = lhs <= rhs
if comparison { return .True(rhs) }
else { return .False }
}
func <=<T : Comparable>(lhs: ComparisonValue<T>, rhs: T) -> ComparisonValue<T> {
switch lhs {
case .True(let lhsValue): return lhsValue <= rhs
case .False: return .False
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment