R4RS and modulo (was: need help understanding modulo)

Quote:

> [...]

> But I actually don't understand *why* R4RS defines modulo and

> remainder in this way. The usual definition of modulo for

> negative arguments (see for example Concrete Mathematics by

> Graham, Knuth & Patashnik or The C Programming Language by

> Kernighan & Ritchie) corresponds to R4RS's definition of

> remainder.

On the contrary, Graham, Knuth and Patashnik (second edition) agree

with Alan Bawden. I checked. Their definition of `mod' for arbitrary

reals is

x mod y = x - y * floor(x/y), for y /= 0 (3.21)

x mod 0 = x (3.22)

and they point out that

0 <= x mod y < y, for y > 0

0 >= x mod y > y, for y < 0.

Note that R4RS defines `modulo' for integers only, with nonzero second

argument.

Graham et al. call `floor(x/y)' the quotient, but it is different from

`quotient' in Scheme. They also call `x mod y' the remainder, but it

is actually a generalisation of `modulo' in Scheme.

Quote:

> Subject: need help understanding modulo

> Date: 12 Sep 1996 05:57:20 -0400

> [...] It's trying to say that if

> (modulo i m) ==> j

> then either 0 <= j < m or m < j <= 0, depending on the sign of m. Just

> like the `mod' function in Common Lisp. [*]

> [...]

> I also often find myself wishing for the function that behaves for `modulo'

> the way that `quotient' behaves for `remainder'. I sure wish Scheme had it.

That would be the `quotient' of Graham, Knuth and Patashnik, or the

two-argument `floor' in Common Lisp, or something like

(lambda (n1 n2) (floor (/ n1 n2)))

in Scheme, right? Call it `quotient-1'. Then, in Scheme, we would

have

(= n1 (+ (* n2 (quotient n1 n2))

(remainder n1 n2)))

and

(= n1 (+ (* n2 (quotient-1 n1 n2))

(modulo n1 n2))).

Somebody tell me if I am mistaken?

Quote:

> -------(footnote)-------

> [*] and if m is zero, it should return i, rather than signaling an error.

> But computer scientists insist on incorrectly thinking of `modulo' as

> having something to do with division, so I've given up arguing this point.

The subtitle to `Concrete Mathematics' is `A foundation for Computer

Science'. I gather they get it right ... and Scheme get it wrong.

Implementations are free to correct this. R4RS fails to specify any

behaviour for `(modulo n 0)'. It will not be portable.

--

Jussi Piitulainen