Order Matters in Function Composition
Composing mappings passes one result into another mapping. Reversing their order can change the result or make the composition undefined.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Work two orders
Let \(f(x)=x+2\) and \(g(x)=3x\). Applying f then g to four gives eighteen. Applying g then f gives fourteen. Composing functions in code uses the same direction of data flow.
Check the middle set
A mapping delivering text is compatible with a second mapping requiring valid integer text only if all the relevant results meet that requirement. The domain and image identify which values should be checked.[1]
Calculate each intermediate value in its own domain
Let \(f(x)=x+2\) and \(g(x)=3x\). Applying \(f\) then \(g\) to four produces eighteen. Applying \(g\) then \(f\) produces fourteen. The operations may share a domain without commuting. See composing two programming functions.
g(f(4)) = g(6) = 18
f(g(4)) = f(12) = 14
General outputs: 3x+6 and 3x+2
Check whether both compositions are even well-defined
A parser from text to integers and a numerical square function can compose in the parse-then-square direction. Squaring raw text has no declared meaning under those contracts. Write domain and codomain for each step before asking if the results agree.