[swift-evolution] Add a `clamp` function to Algorithm.swift

David Sweeris davesweeris at mac.com
Fri Mar 10 14:18:39 CST 2017

> On Mar 10, 2017, at 11:32 AM, Nevin Brackett-Rozinsky via swift-evolution <swift-evolution at swift.org> wrote:
> On Fri, Mar 10, 2017 at 4:16 AM, David Sweeris via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> I’m ok with doing it as an extension on `Comparable`, although we should add an overload for regular ranges, too.
> - Dave Sweeris
> How would the semantics of that work?

Good questions! I was mostly thinking about how often we do stuff like “for i in 0 ..< arr.count”, and that it’d be handy to not have to switch over to using ClosedRange just to be able to clamp to it. To answer your questions, though…

> Should “16.clamped(to: 0..<10)” produce 9 or 10?


> What about “16.clamped(to: 0..<0)”, which is an empty range?

For `Int`? Crash (which, until about 5 minutes ago, is what I thought would happen if you tried to create a range that’s empty like that). For types that support it, I’d say NaN or something like “nil”/“empty” is the most appropriate return value

> Does “16.0.clamped(to: 0..<10)” yield 10.0 or the next-smaller representable Double?

Next-smaller, IMHO. It’s not exactly semantically correct, but AFAIK that’s as correct as Float/Double can be.

Mostly though I’d really like to be able to clamp to array indices, which are pretty much always written as a `Range`, rather than a `ClosedRange`. We could write the function for `Range` to only be generic over `Comparable&Integer`, if the floating point corner cases are too much.

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170310/6d27e075/attachment.html>

More information about the swift-evolution mailing list