[swift-evolution] floating point numbers implicit conversion

David Sweeris davesweeris at mac.com
Sun Jun 18 00:11:41 CDT 2017


Off the top of my head? As the language stands now, maybe a ton of extensions so that it never actually hits the fully generic version?

extension Addable where Self == Int8 {...}
extension Addable where Self == Int16 {...}
extension Addable where Self == Int32 {
  static func + <T: Addable> (lhs: Self, rhs: Int8) -> Self {...}
  static func + <T: Addable> (lhs: Self, rhs: Int16) -> Self {...}
  static func + <T: Addable> (lhs: Self, rhs: Int32) -> Self {...}
  static func + <T: Addable> (lhs: Self, rhs: Int64) -> Int64 {...}
}
extension Addable where Self == Int64 {...}

Dunno if that'll compile... it might need an `_IntNNType` protocol for each integer type so that the where clause could be "where Self: _Int32Type" instead of "where Self == Int32" (of course, if such a thing were actually done, the obvious next step would be to make `UInt64` conform to `_Int8Type`, and see just how close you can get to wat https://www.destroyallsoftware.com/talks/wat).

Even if that works, though, it'll all come crashing down as soon as someone makes an `Int128`... oh, nuts! I forgot about `DoubleWidth`!

Yeah, I don't think I can just pull that particular implementation out of the air.

- Dave Sweeris

> On Jun 17, 2017, at 21:18, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
> 
> And, without integer literals as generic parameters, how would you express this operation?
> 
> 
>> On Sat, Jun 17, 2017 at 23:01 David Sweeris <davesweeris at mac.com> wrote:
>> 
>>> On Jun 17, 2017, at 20:43, Xiaodi Wu <xiaodi.wu at gmail.com> wrote:
>>> 
>>> In Swift, all types and all operators are implemented in the standard library. How do you express the idea that, when you add values of disparate types T and U, the result should be of the type with greater precision? You need to be able to spell this somehow.
>> 
>> Oh, ok... I thought you meant "conditional conformance" or something concrete :-D
>> 
>> Off the top of my head, with "literals as generic parameters",
>> protocol Addable {
>>   associatedtype BitsOfPrecision: IntegerLiteral
>>   static func + <T: Addable> (_: Self, _: T) -> T where T.BitsOfPrecision >
>> BitsOfPrecision
>>   static func + <T: Addable> (_: Self, _: T) -> Self where T.BitsOfPrecision <= BitsOfPrecision
>> }
>> 
>> Although, come to think of it, I suppose that's a bit more than simply using literals as types. Still, it's all information that's available at compile time, though.
>> 
>> - Dave Sweeris 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170617/7c7c929f/attachment.html>


More information about the swift-evolution mailing list