Even and Odd Integers

I've put together a draft proposal for adding isEven, isOdd, and isDivisible to the BinaryInteger protocol. Feedback is always welcome. I'm sure I've absorbed many ideas and examples from the pitch thread by osmosis, so if you feel like you'd like to be included as an author please send me a message and I'll add you.

https://github.com/robmaceachern/swift-evolution/blob/binaryinteger-iseven-isodd/proposals/nnnn-binaryinteger-iseven-isodd-isdivisible.md

After re-reading some of the replies in the pitch thread I decided to include isDivisible in the proposal. There are still some aspects to it that should be discussed:

Signature: How does this look to everyone?

func isDivisible(by denominator: Self) -> Bool

Zeros: What should 12.isDivisible(by: 0) do: trap or return false? Clearly division by zero is undefined, but is divisibility by zero undefined too? I suppose it depends on the precise definition of divisibility.

The Wolfram web console reports an error when the second argument to Divisible[n,m] is zero.

Is 0.isDivisible(by: 0) a special case?

Implementation: Is there a better BinaryInteger implementation than this? (assuming trapping on zero is acceptable)

func isDivisible(by denominator: Self) -> Bool {
    return self % denominator == 0
}
7 Likes