5.3. Composition

As you should expect by now, once you define a new function, you can use it as part of an expression, and you can build new functions using existing functions. For example, what if someone gave you two points, the center of the circle and a point on the perimeter, and asked for the area of the circle?

Let’s say the center point is stored in the variables xc and yc, and the perimeter point is in xp and yp. The first step is to find the radius of the circle, which is the distance between the two points. Fortunately, we have a function, distance, that does that.

double radius = distance (xc, yc, xp, yp);

The second step is to find the area of a circle with that radius, and return it.

double result = area (radius);
return result;

Wrapping that all up in a function, we get:

double fred (double xc, double yc, double xp, double yp) {
  double radius = distance (xc, yc, xp, yp);
  double result = area (radius);
  return result;
}

The name of this function is fred, which may seem odd. I will explain why in the next section.

The temporary variables radius and area are useful for development and debugging, but once the program is working we can make it more concise by composing the function calls:

double fred (double xc, double yc, double xp, double yp) {
  return area (distance (xc, yc, xp, yp));
}

This program shows you how the distance and area functions are composed in the fred function to calculate the area of a circle if we only know the coordinates of the center, and one other point of the circle.

Function composition is not limited to a fixed number of calls. Multiple calls can be made to the same function as well as to a number of different functions.

This program shows how mutliple calls are made to one function and it also shows that calling two or more different functions is valid.

You have attempted of activities on this page