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

Jaden Geller jaden.geller at gmail.com
Fri Mar 10 03:19:36 CST 2017


> On Mar 10, 2017, at 1:13 AM, David Sweeris <davesweeris at mac.com> wrote:
> 
> 
>> On Mar 10, 2017, at 12:22 AM, Jaden Geller via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>>> On Mar 9, 2017, at 11:20 PM, Nicholas Maccharoli via swift-evolution <swift-evolution at swift.org <mailto: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.
> 
> Agreed.
> 
>> 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.
> 
> Yeah, it seems like it’d be technically possible, but not without either a lot of compiler magic (not only in somehow optimizing away the overhead of creating an Array, but `[1, 2].max()` returns an `Int?` instead of an `Int`) , or maybe a sufficiently sophisticated macro… The 1st is something we’re trying to avoid, and IIRC the 2nd is out-of-scope for Swift 4. Also, I’m wary of not having the normal “math.h” functions, simply because they’re so universal.

I suspect the compiler magic wouldn’t be too difficult if the array were a literal, but I don’t know. I forgot that it returns an optional though, that’s definitely problematic and probably a deal-breaker. Perhaps if we ever get vectors (with the size known by the type-system) we could do this (as the result would be non-optional), but I don’t know how it would choose this overload since Array is preferred…

*leaves lid on Pandora’s box and backs away*

> 
> - Dave Sweeris
> 

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


More information about the swift-evolution mailing list