# 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 two functions, f and g. The output of f is used as the input to g.

Figure 4.2: Composition.

We can express this composition with the Scheme expression (g (f x)) where 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 (f 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 x a parameter:

(define fog (lambda (x) (g (f x))))

This defines fog as a procedure that takes one input and produces as output the composition of f and g applied to the input parameter. This works for any two procedures that both take a single input parameter.

We can compose the square and cube procedures from Chapter 3:

(define sixth-power (lambda (x) (cube (square x))))

Then, (sixth-power 2) evaluates to 64.