Skip to main content

Section 4.12 Function Composition

You have probably learned how to evaluate simple expressions like \(\sin(\pi/2)\) and \(\log(1/x)\text{.}\) First, you evaluate the expression in parentheses, which is the argument of the function. Then you can evaluate the function itself, either by hand or by punching it into a calculator.
This process can be applied repeatedly to evaluate more-complex expressions like \(\log(1/\sin(\pi/2))\text{.}\) First we evaluate the argument of the innermost function (\(\pi/2 = 1.57\)), then evaluate the function itself (\(\sin(1.57) = 1.0\)), and so on.
Just as with mathematical functions, C++ functions can be composed to solve complex problems. That means you can use one function as part of another. In fact, you can use any expression as an argument to a function, as long as the resulting value has the correct type:
const double PI = acos(-1.0);  //calculate an accurate value of PI
double x = cos(angle + PI / 2.0);
This statement divides PI by 2.0, adds the result to angle, and computes the cosine of the sum.
Here is another example you may remember from geometry. Given the lengths of legs a and b in a right triangle, you can find the length of the hypotenuse c with \(\sqrt{a^2 + b^2}\text{.}\) Here is that translated to C++
double sideA = 3;
double sideB = 4;
double sideC = sqrt( pow(sideA, 2) + pow(sideB, 2) );
Before sqrt can do its job, we need to compute its argument by doing the +. But before that can happen, the two pow calls must run. So, they happen first. Then their results are added together. Finally, the square root is taken.

Warning 4.12.1.

Just because you can use composition to nest a large number of steps into one line of code, does not mean that you should. This is perfectly legal:
sqrt(pow(hypot(x2 - x1, y2 - y1), 2) + pow(hypot(x4 - x3, y4 - y3), 2) - 2 * hypot(x2 - x1, y2 - y1) * hypot(x4 - x3, y4 - y3) * cos(angleC));
But it is hard to read and will be even harder to debug if you make a mistake somewhere on the line. It also redoes the same work in multiple spots. A better approach would be to write the code as a series of steps that calculate the desired value.
double sideA = hypot(x2 - x1, y2 - y1);
double sideB = hypot(x4 - x3, y4 - y3);
...

Checkpoint 4.12.1.

cmath Which expression correctly computes \(\log_2{(10^8)}\text{?}\) Here is the cmath library for reference.
  • log2(pow(8, 10))
  • That computes 8 to the 10th power.
  • log2(pow(10, 8))
  • log(2, pow(8, 10))
  • There is no log function that takes two parameters.
  • log(2, pow(10, 8))
  • There is no log function that takes two parameters.
  • pow(log2(10), 8)
  • That first does \(\log{2}{10}\text{.}\) We want to first do the pow.
You have attempted of activities on this page.