> On Mar 9, 2017, at 11:20 PM, Nicholas Maccharoli via swift-evolution
> <[email protected]> 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
> <[email protected] <mailto:[email protected]>> 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
> [email protected] <mailto:[email protected]>
> https://lists.swift.org/mailman/listinfo/swift-evolution
> <https://lists.swift.org/mailman/listinfo/swift-evolution>
>
>
> _______________________________________________
> swift-evolution mailing list
> [email protected]
> https://lists.swift.org/mailman/listinfo/swift-evolution
_______________________________________________
swift-evolution mailing list
[email protected]
https://lists.swift.org/mailman/listinfo/swift-evolution