How do I add numbers in Scheme?
Call the + procedure, and give it all of the numbers you want
to add as operands. Here are some examples:
Must all the numbers be integers?> (+ 7 12) 19 > (+ 8149 6622 10986 3414 7306) 36477 > (+ 1 2 -3 4 5 -6 7 8 -9 10 11 -12 13 14 -15 16 17 -18 19 20 -21) 63
They can be any kind of numbers that your implementation of Scheme provides. A few provide only integers, but most support reals, and some support rationals and complex numbers as well. Here are a couple of illustrative interactions with Scheme 48, which supports numbers of all of these types:
There must always be at least two operands, I suppose?> (+ 3/4 -1/3 1/12) 1/2 > (+ 7.2+6.1i -4.3i) 7.2+1.8i
No, you can call the + procedure with only one operand, or
even with none:
The ``sum'' of a single number is that number itself. The ``sum'' of no numbers is the identity for addition, 0. This makes a kind of analogical sense, if you think about it: Since> (+ 42) 42 > (+) 0
(+ 5 5 5) is 15, and
(+ 5 5) is 10, and (+ 5) is 5, the natural next
step in the progression is that (+) is 0.
Why would anyone ever want to call + with fewer than two
operands?
As we'll see later on, a programmer sometimes
wants to call a procedure like + without knowing in advance
how many operands to give to it! Defining the ``trivial'' cases of fewer
than two operands ensures that such calls will always succeed and deliver
plausible results.
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/plus.html