What about division, then? How do I divide one integer by another in Scheme?
Division is more complicated than addition, subtraction, and
multiplication, because dividing one integer by another gives two results,
a quotient and a remainder. Since the programmer might want either (or
both) of these, Scheme provides two separate procedures,
quotient (which returns the integer quotient and discards the
remainder) and remainder (which returns only the remainder):
Can the dividend and the divisor be negative?> (quotient 45 6) 7 > (remainder 45 6) 3
Yes. The quotient is positive (or zero) if they have the same sign; it's negative (or zero) if they have opposite signs:
What happens if I give the> (quotient -45 6) -7 > (quotient 45 -6) -7 > (quotient -45 -6) 7 > (quotient 6 -45) 0
quotient procedure a different
number of operands?
This is always an error. Quotient must receive exactly
two arguments, or your program won't work:
And the arguments must be integers, even if other kinds of numbers are also supported by the implementation:> (quotient 5) quotient: wrong number of arguments > (quotient 2520 3 5 7) quotient: wrong number of arguments
> (quotient 15.4 7) quotient: wrong argument type real (expected integer)
What happens if I try to divide by 0?
It doesn't work any better in Scheme than it did in your arithmetic class when you were eight years old. In most implementations, your program halts and you get an advisory message:
Some implementations may return a special representation for ``infinity'' or ``undefined,'' and just keep going, in the hope that the program won't try to use the computed value for anything important:> (quotient 7 0) quotient: argument out of range: 0
In other words, the result is unpredictable, so don't divide by zero.> (quotient 7 0) +#
Next topic
Previous topic
Table of contents
This document is available on the World Wide Web as
http://www.math.grin.edu/~stone/scheme-web/quotient.html