4.2 Composing procedures
One way to divide a problem is to split it into steps where the output of the first step is the input to the second step, and the output of the second step is the solution to the problem. Each step can be defined by one procedure, and the two procedures can be combined to create one procedure that solves the problem.
Figure 4.2 shows a composition of
g. The output of f is used as the input to
We can express this composition with the Scheme expression
(g (f x))
x is the input. The written order appears to be reversed from
the picture in Figure 4.2. This is
because we apply a procedure to the values of its subexpressions: the
values of the inner subexpressions must be computed first, and then used
as the inputs to the outer applications. So, the inner subexpression
x) is evaluated first since the evaluation rule for the outer
application expression is to first evaluate all the subexpressions.
To define a procedure that implements the composed procedure we make
This defines fog as a
procedure that takes one input and produces as output the composition of
g applied to the input parameter. This works for any two
procedures that both take a single input parameter.
We can compose the
cube procedures from Chapter 3:
(sixth-power 2) evaluates to