This page is part of the web mail archives of SRFI 77 from before July 7th, 2015. The new archives for SRFI 77 contain all messages, not just those from before July 7th, 2015.
bear <bear@xxxxxxxxx> writes: > For what it's worth, here is the behavior that I as a programmer > expect from Div and Mod. > > I expect mod always to return a number between zero inclusive and the > modulus exclusive. I agree. Haskell has two pairs of functions, where functions in each pair are consistent with each other in the obvious way: quot & rem - quot is rounded towards zero, the sign of rem is the sign of the dividend div & mod - div is rounded towards negative infinity, the sign of mod is the sign of the divisor (Plus quotRem and divMod which compute both together.) | quot rem div mod -----------+------------------- 123 10 | 12 3 12 3 -123 10 | -12 -3 -13 7 123 -10 | -12 3 -13 -7 -123 -10 | 12 -3 12 -3 Both are primarily used with a positive divisor, in which case they agree on non-negative dividends and provide two most common variants on negative dividends. The div & mod variant is more regular mathematically. When the divisor is a power of 2, it corresponds to bit shifts and masks. Knuth warns about programming languages which understand div & mod differently than this way. The quot & rem variant is consistent with Intel processors and C99, absolute values of results are determined by absolute values of arguments. The GMP library provides the above two families plus a yet another one, rounding towards positive infinity. I dislike using an entirely different variant when the divisor is negative. If the variant with rounding to nearest is worth providing, it should be a separate pair of functions. It's not clear how to break ties: there are various subvariants possible. -- __("< Marcin Kowalczyk \__/ qrczak@xxxxxxxxxx ^^ http://qrnik.knm.org.pl/~qrczak/