Add clamp(value: Bound) -> Bound to ClosedInterval


(Lily Ballard) #1

I'd like to see ClosedInterval gain a new method

    /// Returns `value` clamped to `self`.
    func clamp(value: Bound) -> Bound

This can't go on HalfOpenInterval (and therefore can't go on IntervalType) because a half-open interval doesn't have a known largest-contained-value (and in fact it can be empty), but it's perfectly reasonable for ClosedInterval to have this.

-Kevin Ballard


(Dave Abrahams) #2

It's well-defined when the value is an Index (has discreet values). But
that whole protocol is probably not long for this world...
(https://github.com/apple/swift/blob/master/test/Prototypes/CollectionsMoveIndices.swift)

···

on Wed Feb 17 2016, Kevin Ballard <swift-evolution@swift.org> wrote:

I'd like to see ClosedInterval gain a new method

    /// Returns `value` clamped to `self`.
    func clamp(value: Bound) -> Bound

This can't go on HalfOpenInterval (and therefore can't go on
IntervalType) because a half-open interval doesn't have a known
largest-contained-value (and in fact it can be empty), but it's
perfectly reasonable for ClosedInterval to have this.

--
-Dave


(Lily Ballard) #3

You're right, clamp() can be well-defined for HalfOpenInterval if the value conforms to some protocol that enables the ability to find the previous value (such as BidirectionalIndexType), although it would have to return an optional value in that case since the interval itself may be empty.

But I don't have any particularly compelling reason to care about having clamp() for HalfOpenIntervals anyway, since all of my own uses have been with floating-point values.

-Kevin Ballard

···

On Wed, Feb 17, 2016, at 05:10 PM, Dave Abrahams via swift-evolution wrote:

on Wed Feb 17 2016, Kevin Ballard <swift-evolution@swift.org> wrote:

> I'd like to see ClosedInterval gain a new method
>
> /// Returns `value` clamped to `self`.
> func clamp(value: Bound) -> Bound
>
> This can't go on HalfOpenInterval (and therefore can't go on
> IntervalType) because a half-open interval doesn't have a known
> largest-contained-value (and in fact it can be empty), but it's
> perfectly reasonable for ClosedInterval to have this.

It's well-defined when the value is an Index (has discreet values). But
that whole protocol is probably not long for this world...
(https://github.com/apple/swift/blob/master/test/Prototypes/CollectionsMoveIndices.swift)