Forty-two wears a different hat

Two numbers have ordered division. One expects a fractional answer. The other wants whole groups and somewhere to put a possible failure.

The slash keeps its fraction

In released Pooka, / returns a Float, including when both operands are integers:

main() {
  assert 7 / 2 == 3.5
  assert 4 / 2 == 2.0
  assert 7.0 / 2 == 3.5
  assert 7 / 2.0 == 3.5
}

The result type does not change according to whether a particular quotient happens to be whole. Even 4 / 2 remains floating-point division.

That gives the type checker one consistent rule for the operator. The source’s numeric types still need checking; two strings cannot acquire a useful division merely by standing on either side of a slash.

Ask for whole groups explicitly

Truncating integer division belongs to the standard library:

import pooka/int

main() {
  assert int.divide(7, 2) == Ok(3)
  assert int.divide(-7, 2) == Ok(-3)
  assert int.divide(7, -2) == Ok(-3)
  assert int.divide(7, 0) == Error(int.MathError.DivisionByZero)
}

Here the API returns a Result. Success carries an integer; a zero divisor has an explicit error value. “Truncate towards zero” is more precise than “round down”, especially when the answer is negative.

Give Erlang the right operation

The distinction also exists below the language surface:

7 div 2.
7.0 / 2.

These evaluate to 3 and 3.5. Pooka’s slash follows floating-point division, while the integer helper uses the whole-number operation behind its checked public API.

A return type is part of a contract, not merely a convenient way to print the answer. Turning a zero divisor into an ordinary error value requires the library function to do that work. The bare operator does not silently grow a recoverable Error branch.

This is why arithmetic examples need deliberately awkward inputs. A comparison that forgets the difference between 2 and 2.0 can conceal the very rule it was supposed to explain.

The numbers can keep their hats. The call site should say which answer it is asking them to bring back.

— Peregrine Finch

· pooka, numbers, erlang