[swift-evolution] divisible-by operator

Jacob Bandes-Storch jtbandes at gmail.com
Sun Apr 10 20:39:58 CDT 2016


I'm not suggesting this for the standard library (or anyone's production
code), but it's fun to note that there is actually a standard mathematical
notation for this, and it has a corresponding Unicode character U+2223
"DIVIDES": ∣

    infix operator ∣ {}
    func ∣<I: IntegerType>(lhs: I, rhs: I) -> Bool {
        return rhs % lhs == 0
    }

    3 ∣ 12  // true
    4 ∣ 12  // true
    5 ∣ 12  // false


Jacob

On Thu, Apr 7, 2016 at 11:13 AM, Milos Rankovic via swift-evolution <
swift-evolution at swift.org> wrote:

> Thank you for giving this a thought!
>
> milos
>
> On 7 Apr 2016, at 15:13, Erica Sadun <erica at ericasadun.com> wrote:
>
>
> On Apr 6, 2016, at 10:13 AM, Milos Rankovic via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Checking for divisibility is very common:
>
>     21 % 3 == 0 // true
>
> In fact, this is such a common use of the `%` operator that the `== 0`
> side of the expression seems distracting in this use case. For quite a
> while now, I’ve been using a custom operator for this, which is steadily
> growing on me:
>
>     21 %== 3 // true
>
> … which also allows me to overload it for sequences:
>
>     21 %== [7, 3] // true
>
> (If I’m inadvertently misusing this mailing list to share such a minor
> idea, please tell me off so that I can learn not to do it again!)
>
>
> While modulo checks are common, I don't think that your proposed solution
> (%==) enhances readability or saves typing **to such extent** that it
> vastly improves over the existing art:
>
> 21 % 3 == 0 reads easily from left to right, is quick to type, is
> understood across many languages.
>
> 21 %== 3    saves a few spaces, is less immediately understandable (due
> to the visual overlap with `+=` and `-=`) and would be (as far as I'm aware
> of) unique to Swift.
>
> I applaud the thinking and creativity but I would not support the proposal.
>
> -- E
>
>
>
> _______________________________________________
> 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/20160410/b98e3818/attachment.html>


More information about the swift-evolution mailing list