[swift-evolution] [Pitch] Add the sign method to the SignedNumberType protocol.

Dany St-Amant dsa.mls at icloud.com
Mon May 23 14:19:10 CDT 2016


> Le 22 mai 2016 à 03:07, Adam Nemecek via swift-evolution <swift-evolution at swift.org> a écrit :
> 
> Howdy,
> I think that the SignedNumberType should implement a method called sign that will return -1 for negative numbers, 0 for 0 and 1 for positive numbers. This is similar to the signum method in e.g. Java and similarly called methods in other languages.
> 
> The implementation is fairly straight forward
> 
> extension SignedNumberType {
>   var sign: Self {
>     if self == 0 {
>       return 0
>     }
>     else if self > 0 {
>       return 1
>     }
>     return -1
>   }
> } 
> 
> I was trying to implement is without branching by doing (x > 0) - (x < 0) but I couldn't get the types right so I'm open to suggestions.
> 

Challenge accepted… Removed the if/else if, at the cost of double function call to a tri-op:

extension Bool {
    func as01<T:SignedNumberType>() -> T { return self ? 1 : 0 }
}

extension SignedNumberType {
    var sign: Self { return (self > 0).as01() - (self < 0).as01() }
}


Dany
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160523/81a73fdf/attachment.html>


More information about the swift-evolution mailing list