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

David Sweeris davesweeris at mac.com
Fri Mar 10 03:13:28 CST 2017


> On Mar 10, 2017, at 12:22 AM, Jaden Geller via swift-evolution <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.

- Dave Sweeris

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


More information about the swift-evolution mailing list