Scheme unusually allows procedures within procedures. That nesting lets you easily reuse commonly repeated code and also adds organizational possibilities to your code base.
For instance, I once had to write a simple procedure for finding the maximum of four numbers. Without using the
max procedure built into Scheme, that is.
This is just one way of doing it, but it’s a pretty clever way.
; maximum ; a,b,c,d - numeric arguments to determine which is the largest ; returns - largest numeric argument (define (maximum a b c d) ; second procedure, within the first ; maxi ; x,y - numeric arguments to determine which is the largest ; returns - largest numeric argument (define maxi x y) (if (< x y) x y) ) ; magic happens here, reusability! (maxi a (maxi b (maxi c d))) )
With this code, imagine the arguments were 1 2 3 4. The first
maxi would decide which of 3 4 is larger. Then, it would hand it off to the next
maxi up the chain, and it would decide which of 2 4 is larger, and so on until it gets to simply 4 as being the largest. Imagine you were then asked to increase the argument length to include 10 numbers, save the updating of the new argument names, all it takes is adding enough
maxi calls to deal with 10 numbers (which would be 9 by the way).
Keep in mind though that this is not Scheme specific. This would work in Java the same way as well, but you would need two methods in a class to deal with it. Luckily, Java has the
private keyword which makes it very similar to the way
maxi is visible to the outside work: it is not.