Created
March 26, 2015 23:15
-
-
Save JadenGeller/a818afd3733b942ae676 to your computer and use it in GitHub Desktop.
Swift Inequality Interval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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