diff --git a/StandardLibrary/Sources/Core/Range.hylo b/StandardLibrary/Sources/Core/Range.hylo index cb3059b0e..4ab0a0a4f 100644 --- a/StandardLibrary/Sources/Core/Range.hylo +++ b/StandardLibrary/Sources/Core/Range.hylo @@ -1,5 +1,5 @@ -/// A half-open interval from a lower bound up to, but not including, an uppor bound. -public type Range { +/// A half-open interval from a lower bound up to, but not including, an upper bound. +public type Range { // TODO: private(set) /// The minimum value included in `self`. @@ -13,17 +13,24 @@ public type Range { memberwise init /// Creates a half-open interval [`lower_bound`, `upper_bound`). - /// - /// - Requires: `lower_bound <= upper_bound`. + /// - Requires: `lower_bound <= upper_bound` if `Bound` models `Comparable`. public init(from lower_bound: sink Bound, up_to upper_bound: sink Bound) { - // precondition(lower_bound <= upper_bound) &self.lower_bound = lower_bound &self.upper_bound = upper_bound } - /// Returns `true` iff `element` is contained in `self`. - public fun contains(_ element: Bound) -> Bool { - (element >= lower_bound) && (element < upper_bound) + /// Returns true iff `lower_bound == upper_bound`. + public fun is_empty() -> Bool { + lower_bound == upper_bound + } + +} + +public extension Range where Bound: Comparable { + + /// Returns `true` iff `x` is contained in `self`. + public fun contains(_ x: Bound) -> Bool { + (x >= lower_bound) && (x < upper_bound) } /// Returns `true` iff `other` is contained in `self`. diff --git a/Tests/LibraryTests/TestCases/RangeTests.hylo b/Tests/LibraryTests/TestCases/RangeTests.hylo index 86ea05660..1d2e2d884 100644 --- a/Tests/LibraryTests/TestCases/RangeTests.hylo +++ b/Tests/LibraryTests/TestCases/RangeTests.hylo @@ -1,6 +1,6 @@ //- compileAndRun expecting: success -public fun test_conformance_to_iterator() { +private fun test_conformance_to_iterator() { var r = 1 ..< 3 var x: Int @@ -14,6 +14,18 @@ public fun test_conformance_to_iterator() { precondition(r.lower_bound == r.upper_bound) } +private fun test_non_comparable() { + struct NonComparable: SemiRegular { + public memberwise init + let x: Int + } + + var r0 = NonComparable(0) ..< NonComparable(0) + precondition(r0.is_empty()) + var r1 = NonComparable(0) ..< NonComparable(1) + precondition(!r1.is_empty()) +} + public fun main() { let r0 = Range(from: 0, up_to: 10) @@ -27,4 +39,5 @@ public fun main() { precondition(!r0.contains(5 ..< 15)) test_conformance_to_iterator() + test_non_comparable() }