#include <stdio.h> #include <stdlib.h> typedef int(*intfunc_t)(int); typedef struct { intfunc_t call; intfunc_t first; intfunc_t second; } composed_func; void compose(intfunc_t a, intfunc_t b, composed_func *ret){ ret->first = a; ret->second = b; int f(int n){ return((*(ret->first))((*(ret->second))(n))); } ret->call = &f; } int main(){ int n = arc4random() % 64; int f(int n){ return n << 1; } printf("f(%d) = %d\n", n, f(n)); printf("f(f(%d)) = %d\n", n, f(f(n))); composed_func c; compose(f, f, &c); printf("compose(f,f)(%d) = %d\n", n, c.call(n)); return 0; }
#include <stdlib.h> #include <stdio.h> #define COMPOSE(f, g) ({ int fog(int n) { return f(g(n)); } fog; }) int f(int n) { return n << 1; } int main(void) { printf("(f ° f)(16) = %d\n", COMPOSE(f, f)(16)); printf("(f ° f ° f)(16) = %d\n", COMPOSE(f, COMPOSE(f, f))(16)); return 0; }