
Sponsored
Sponsored
Iterative Approach: In this approach, we compose the functions iteratively from the last function to the first. This is because function composition works in reverse order, i.e., f(g(h(x))) means first apply h, then g, and finally f. We start with the input value x and apply each function in the function list from right to left.
Time Complexity: O(n) where n is the number of functions.
Space Complexity: O(1) since we are using a fixed amount of extra space.
This C solution defines an array of function pointers and iterates over the functions from right to left, applying each one to the initial input. Each function is applied in turn, modifying the input, and the final result is returned.
Recursive Approach: This approach encapsulates the recursive function composition in a way that it applies the last function first and makes a recursive call to apply the rest. We either call the next composed function recursively until the base case, i.e., no functions left, is reached, or upon an empty function list, return the input as it is simply the identity function.
Time Complexity: O(n) where n is the number of functions.
Space Complexity: O(n) due to the recursive call stack.
1#include <stdio.h>
2
3int identity(int x) { return x; }
4
5int recursiveCompose(int (*functions[])(int), int length, int x) {
6 if (length == 0) return identity(x);
7 int lastFunctionResult = functions[length - 1](x);
8 return recursiveCompose(functions, length - 1, lastFunctionResult);
9}
10
11int addOne(int x) { return x + 1; }
12int square(int x) { return x * x; }
13int doubleValue(int x) { return 2 * x; }
14
15int main() {
16 int (*functions[])(int) = { addOne, square, doubleValue };
17 int x = 4;
18 int result = recursiveCompose(functions, 3, x);
19 printf("%d\n", result);
20 return 0;
21}This C implementation defines a recursive function which applies the last function in the array and then calls itself with the remaining functions one less in length, composed into a single final result.