[swift-evolution] [Pitch] 'Double modulo' operator
Stephen Canon
scanon at apple.com
Mon May 23 09:30:17 CDT 2016
I’m not really sold on the `%%` spelling, but I think the operation itself is worth exposing. This is the remainder of a “flooring” division (as opposed to the C-family “truncating” division[1]). If we do provide it, we should also provide the accompanying divide operation.
– Steve
[1] there are several other ways to define division beyond these two: remainder is always positive, remainder is closest to zero, etc. Truncating and flooring division are the most common by a wide margin, however.
> On May 21, 2016, at 4:22 PM, Adam Nemecek via swift-evolution <swift-evolution at swift.org> wrote:
>
> Hello,
>
> I think that Swift could use the 'double modulo' operator which is for example in CoffeeScript (some discussion can be found here https://github.com/jashkenas/coffeescript/issues/1971 <https://github.com/jashkenas/coffeescript/issues/1971>).
>
> This operator, unlike normal modulo, takes sign from the divisor, not the dividend e.g. -10 % 3 == -1, but -10 %% 3 == 2.
>
> In practice, this operator is useful for 'cyclical' indexing. For example, it would be useful for calculating the real index into a collection when we are using an index outside of the range of valid indices and could be used to index into a collection using a negative index à la Python and Ruby (where [1,2,3,4][-1] == 4).
>
>
> The implementation would probably be something along these lines:
>
> infix operator %% {
> associativity left
> precedence 150
> }
>
> func %%<T: IntegerArithmeticType>(lhs:T, rhs:T) -> T {
> return (lhs % rhs + rhs) % rhs
> }
>
> If accepted, this could be later incorporated into a method or operator that works directly with collections using their count property.
> Maybe the syntax could be something like [1,2,3,4] %% -1 == 4.
>
> Ideas, suggestions?
> _______________________________________________
> 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/20160523/e728ecc3/attachment.html>
More information about the swift-evolution
mailing list