[erlang-questions] divrem eep?

Richard A. O'Keefe ok@REDACTED
Fri Aug 22 00:43:22 CEST 2014

On 22/08/2014, at 8:34 AM, Tony Rogvall wrote:
> After looking around a bit I found the following languages having a divrem / divmod build in function / operator!
> Haskell: quotRem, divMod
> Python: divmod
> Ruby: divmod
> Visual Basic: DivRem
> C#: DivRem
> C++: DivRem
> JScript: DivRem
> C: div / ldiv

C++ *does* have C's div()/ldiv().  I have been
unable to locate any DivRem in the standard; which
section is it in?

You missed Lisp
  (floor X Y)
  (ceiling X Y)
  (round X Y)
  (truncate X Y)
all return two values, a quotient and a remainder.
If there is any language other than a dialect of
Lisp that supports all four, I don't know what it
might be.

You also missed Pop-2.

And also SML, where the IntInf structure has
divMod (x, y) -> (q, r)   (* flooring quotient and remainder *)
quotRem (x, y) -> (q, r)  (* truncating quotient and remainder *)
but strangely, fixed size integers do _not_ have these

> So why don't we ? 

I think you may have misunderstood the reason that C has
div().  It's not for efficiency, it's for portability.
C originally specified / and % to do whatever the hardware
did.  C89 introduced div() in order to provide a form of
integer division that was supposed to give you the same
results everywhere.

One of the sad things about the change from SPARC V8 to
SPARC V9 was that you weren't any longer supposed to
get the remainder as well as the quotient from a divide
instruction.  (Holy VAX, Batman!)  So x % y is implemented
as x - (x/y)*y.  At least the Solaris Studio compiler
    a = x/y;
    b = x%y;
    a = x/y;
    b = x - a*y;

This shows that C does not need div() for *efficiency*,
because you can get whatever efficiency that might offer
without it.

SML shows clearly that bignums are an important reason
for the existence of such a function at some level, but
C compilers show it doesn't have to be the source level.

More information about the erlang-questions mailing list