Created
February 7, 2023 00:32
-
-
Save gdetor/c038f0fc7604feda11c5c54294bd6d99 to your computer and use it in GitHub Desktop.
Closure in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef struct TClosure { | |
int (*code)(struct TClosure *env, int); | |
int state; | |
} Closure; | |
int call(Closure *c, int x) { | |
return c->code(c, x); | |
} | |
int adder_code(Closure *env, int x) { | |
return env->state + x; | |
} | |
int multiplier_code(Closure *env, int x) { | |
return env->state * x; | |
} | |
Closure make_closure(int op, int k) { | |
Closure c; | |
c.state = k; | |
c.code = (op == '+' ? adder_code : multiplier_code); | |
return c; | |
} | |
int main(int argc, const char *argv[]) { | |
Closure c1 = make_closure('+', 10); | |
Closure c2 = make_closure('*', 3); | |
printf("c1(3) = %i, c2(3) = %i\n", | |
call(&c1, 3), call(&c2, 3)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment