In the examples you've shown so far, there's only one arithmetic operation. Can Scheme evaluate more complicated arithmetic expressions, ones that involve lots of different operations?
Yes. In the previous examples, each of the operands was expressed as a numeral, but that was just to keep the examples simple while the effects of the integer procedures were being explained. Scheme allows the programmer to express operand values in a variety of ways, including procedure calls.
How does that work? Do you just put a procedure call in place of the numeral?
Sure. Suppose, for example, you want to compute the product of seven minus three and five plus twelve. There's a slow way to do it, step by step, using only numerals as arguments:
But you'd rather just type in an expression in which the procedure calls are nested, and let Scheme keep track of the intermediate results:> (- 7 3) 4 > (+ 5 12) 17 > (* 4 17) 68
Make sure that you retain the left parenthesis at the beginning of each procedure call and the matching right parenthesis at the end, just after the last argument. If you leave out any of the parentheses, Scheme won't be able to work out the nesting correctly.> (* (- 7 3) (+ 5 12)) 68
Can the numerals in the nested procedure calls also be replaced with procedure calls?
Yes. Scheme will not complain if you give it a complicated expression, such as
> (* (quotient (* 7 41) (- (max 38 14) 35))
(abs (+ 34 (min 5 (gcd 40 1385) 29 13))))
3705
How many levels of nesting are permitted?
In theory, there is no limit. In practice, some implementations of Scheme do impose a limit, but you're not likely to encounter it. Your ability to write intelligible expressions using many levels of nesting will probably give out before Scheme's ability to interpret such expressions. Besides, particularly with arithmetic expressions, it's rare to encounter a long, complicated calculation in which the intermediate results are completely uninteresting. The ones that do crop up tend to be things like adding a column of figures, which you can do in Scheme with no nesting of procedure calls at all.
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/nested-calls.html