[swift-evolution] protocol-oriented integers (take 2)

Haravikk swift-evolution at haravikk.me
Tue Jan 31 17:39:29 CST 2017


> On 31 Jan 2017, at 20:53, Max Moiseev via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi Brent,
> 
> Thanks a lot for your suggestions! After having discussed them with Dave, we came up with the following design that I personally like a lot.
> 
> enum Overflowing { case .withOverflow }
> enum FullWidth { case .fullWidth }
> 
> protocol FixedWidthInteger {
>  func adding(_ other: Self, _: Overflowing) -> (partialValue: Self, overflow: ArithmeticOverflow)
>  func subtracting(_ other: Self, _: Overflowing) -> (partialValue: Self, overflow: ArithmeticOverflow)
>  func multiplied(by other: Self, _: Overflowing) -> (partialValue: Self, overflow: ArithmeticOverflow)
>  func divided(by other: Self, _: Overflowing) -> (partialValue: Self, overflow: ArithmeticOverflow)
> 
>  func multiplied(by other: Self, _: FullWidth) -> DoubleWidth<Self>
>  func dividing(_ other: DoubleWidth<Self>, _: FullWidth) -> (quotient: Self, remainder: Self)
> }
> 
> 
> Call sites would look like:
> 
> x.multiplied(by: y, .withOverflow) and x.multiplied(by: y, .fullWidth)
> 
> a little different for the division:
> 
> x.divided(by: y, .withOverflow) and y.dividing(x, .fullWidth)
> 
> Note the inverse-ness of `dividing`, but the lack of the argument label makes it quite natural.

While I applaud the ingenuity behind this solution, it seems an odd thing to do, and I wonder if it's something that might become obsolete in the future?

I mean, since the purpose of this is just to select the correct method declaration, then the more "correct" way to do this would be using labelled Void arguments, but of course these aren't as neat right now:

	protocol FixedWithInteger {
		func adding(_ other:Self, withOverflow:Void) -> (partialValue:Self, overflow:ArithmeticOverflow)
	}

	x.add(y, withOverflow:())

This uses the method's label to avoid the need to declare enums purely for selection. The problem is of course that the syntax isn't that great because of the extraneous :(). It would be better if we could just do x.add(y, withOverflow:), but that might be ambiguous because using labels without values is how we select labelled functions (e.g- let f = adding(:withOverflow:) would select the method).

I'm just wondering if there's a change to labelled void arguments that we could make that would allow that style to be used instead? It just feels to me like using a labelled Void is the "proper" way to achieve what is needed, and that using enums just because it isn't possible right now is something that could become obsolete in future.

- Haravikk
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170131/2265c7b8/attachment.html>


More information about the swift-evolution mailing list