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

Jaden Geller jaden.geller at gmail.com
Fri Mar 10 02:22:40 CST 2017


> On Mar 9, 2017, at 11:20 PM, Nicholas Maccharoli via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Nevin,
> 
> Yeah I think this works well as an extension on `Comparable`,  `foo.clamped(to: 1...100)` seems pretty natural.
> 
> Why not go one step further and move the versions of min, max that take two arguments on over to `Comparable` as a protocol extension?

I think that a symmetric operation like `min` or `max` ought to treat both arguments in a symmetric way. `3.max(with: 9)` not only reads badly, but privileges one argument over the other syntactically. I’d very much like to avoid this.

I would be okay with removing top-level min and max if `Array` min and max could generate equivalent code given an array literal. This seems possible.

> 
> Perhaps something like this?
> 
> extension Comparable {
> 
>     func max(with value: Self) -> Self {
>         if value > self {
>             return value
>         }
>         return self
>     }
> 
>     func min(with value: Self) -> Self {
>         if value < self {
>             return value
>         }
>         return self
>     }
> 
>     func clamped(to range: ClosedRange<Self>) -> Self {
>         let selfUpperMin = range.upperBound.min(with: self)
>         return range.lowerBound.max(with: selfUpperMin)
>     }
> }
> 
> - Nick
> 
> 
> On Fri, Mar 10, 2017 at 1:41 PM, Nevin Brackett-Rozinsky via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
> I’d be on board with an extension of Comparable so you could write “16.clamped(to: 0...10)”. Something along the lines of:
> 
> extension Comparable {
>     func clamped(to range: ClosedRange<Self>) -> Self {
>         return max(range.lowerBound, min(self, range.upperBound))
>     }
> }
> 
> Nevin
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution

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


More information about the swift-evolution mailing list