Unexpected behaviour of the modulo operator

I've noticed that the % methods on builtins behaves quite unfortunate (imo) when applied to negative numbers

Now, i am aware that mathematically it is undefined how it should behave with negative numbers, however basically every language i have worked in agreed that -1 % 10 should evaluate to 9.
This has the benefit that, when e.G. calculating a random ISize in a range 0 to 100, one would get away with rand.isize() % 100 rather than the more awkward rand.usize().isize() % 100 or (rand.usize() % 10).isize()

Similarly, when moving on a taurus positions could be calculated simply by something like primitive Up fun apply(x, y): (ISize, ISize) => (x, (y - 1) % 10)
compared to the more verbose

primitive Up
  fun apply(x, y): (ISize, ISize) =>
    if y <= 0 then
      (x, 10)
    else
      (x, y - 1)
    end

So I'm wondering if pony has any good reason for deviating from this behavior and choosing to return the negative remainder instead?

Posted Mar 29, 2018, 9:50 AM UTC

31
SaltTM•

you'll get a quicker response on github issue tracker.

2
spreadLinkOP•

This doesn't feel like an appropriate question to open an issue for. It's not necessarily a wrong implementation as much as one that I just didn't expect.

I assume this is feasible for the rfc-tracker instead, but I wanted to hear if there are any obvious statements (like there are for /0) about it that I had missed before going that route.

It's also not exactly troubling to write an interface which overrides this behaviour, so I figured an open discussion would be better suited for it, if that makes sense.

1
SaltTM•

check the main site for the irc info

1
spreadLinkOP•

I know about the IRC channel, but the question seemed a bit too long for it. It is also awkward to share code-samples there without relying on a gist or w/ever

Edit: typo

1
SaltTM•

I mean you already posted it here, you can just link it now.

1
sasmithjr•

While I have nothing to back this up, I think it might be that % is remainder and not mod in order to match how C/C++ use the operator.

Edit: From C99 (found here), Section 6.5.5:

the result of the `% operator is the remainder

If the quotient a/b is representable, the expression (a/b)*b + a%bshall equala`

Edit2: Additionally, % as remainder maps nicely to the LLVM IR srem. Source.

2
spreadLinkOP•

Ye this makes sense. It's an unfortunate naming decision then.

Time to write a RealMod interface ;)

1