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

David Sweeris davesweeris at mac.com
Tue May 24 13:59:57 CDT 2016


That depends... Does “x = a ? b : c” and "if a {x = b} else {x = c}” compile down to the same machine code? I know of one arch where “?:” takes 0 cycles, but I don’t know if there’s a difference on x86 or ARM.

Either way, I’d think that just doing the comparison within `sign` would be faster, since it doesn’t create two extra Bools and SignedNumberTypes.

- Dave Sweeris

> On May 24, 2016, at 6:33 AM, Haravikk via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On 23 May 2016, at 20:19, Dany St-Amant via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>> 
>> 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() }
>> }
> 
> I don’t believe this solves the problem; I think you’ve really just moved the branching into the as01() method.
> 
> I think the more correct solution would be for all integer types to have a required Bool initialiser in a protocol somewhere, this way you could just do:
> 
> 	var sign:Self { return Self(boolValue: self > 0) - Self(boolValue: self < 0) }
> 
> Since all integer types should be able to do this by just extending the value to fit, rather than testing it. I’m not completely up-to-date on the integer changes that will be in Swift 3, but perhaps conversion from bool will be easier in future, in Swift 2.2 it’s not really treated as a number type for conversion purposes, which is disappointing.
> 
> Also apologies for my initial misunderstanding of the need for this sign property, no idea how I managed to get such a mental block as it’s obviously very useful for multiplication when account for sign and a few other cases. Anyway, I’m a +1, though implementation is definitely trickier than it seems it should be, thanks to some of Swift’s number-related quirks!
> _______________________________________________
> 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/20160524/f8e00612/attachment.html>


More information about the swift-evolution mailing list