Writing a Function as a Composition
When you're given a multi-step task to perform, you may want to break it into pieces, and assign different pieces to different people.
When you're given a function that does several things, you may want to break it into ‘smaller’ functions that accomplish the same job!
Example (Breaking a Composite Function Into Pieces)
This function $\,h\,$ does the following:
- Subtracts $\,4\,$
- Cubes the result
- Multiplies by $\,5\,$
- Subtracts $\,7\,$
Break these four tasks into two pieces, as shown in the mapping diagram below:
- Assign the first two tasks (subtract $\,4\,,$ then cube) to $\,f\,$: $$\cssId{s15}{f(x) = (x-4)^3}$$
- Assign the last two tasks (multiply by $\,5\,,$ then subtract $\,7\,$) to $\,g\,$: $$\cssId{s19}{g(x) = 5x - 7}$$
With these assignments, the composite function $\,g\circ f\ $ (where $\,f\,$ acts first, followed by $\,g\,$) accomplishes the same thing as $\,h\,$:
$$ \begin{align} &\cssId{s24}{(g\circ f\,)(x)}\cr\cr &\qquad \cssId{s25}{= g(f(x))}\cr\cr &\qquad \cssId{s26}{= g\bigl((x-4)^3\bigr)}\cr\cr &\qquad \cssId{s27}{= 5(x-4)^3 - 7}\cr\cr &\qquad \cssId{s28}{= h(x)} \end{align} $$You Can Break a Task Into Pieces In Different Ways!
Of course, you can delegate the responsibilities in different ways:
-
$f\,$ takes the first step (subtract $\,4\,$): $$\cssId{s32}{f(x) = x-4}$$
$g\,$ takes the other three steps (cube, multiply by $5$, subtract $\,7\,$): $$\cssId{s34}{g(x) = 5x^3 - 7}$$
-
$f\,$ takes the first three steps (subtract $\,4\,,$ cube, multiply by $\,5\,$): $$\cssId{s36}{f(x) = 5(x-4)^3}$$
$g\,$ takes the last (subtract $\,7\,$): $$\cssId{s38}{g(x) = x - 7}$$
In both cases, be sure to check that $\,(g\circ f\,)(x) = h(x)\,.$
You Can Use More Than Two Helpers!
Or, you can use more ‘helper’ functions. For example:
-
Let $\,a\,$ subtract $\,4\,$: $$a(x) = x-4$$
-
Let $\,b\,$ cube: $$b(x) = x^3$$
-
Let $\,c\,$ multiply by $\,5\,$ and subtract $\,7\,$: $$c(x) = 5x - 7$$
Then:
$$ \begin{align} &\cssId{s47}{(c\circ b\circ a\,)(x)}\cr\cr &\qquad \cssId{s48}{= c(b(a(x)))}\cr\cr &\qquad \cssId{s49}{= c(b(x-4))}\cr\cr &\qquad \cssId{s50}{= c((x-4)^3)}\cr\cr &\qquad \cssId{s51}{= 5(x-4)^3 - 7}\cr\cr &\qquad \cssId{s52}{= h(x)} \end{align} $$The exercises in this lesson give you practice with this process of writing a function as a composition.