Skip to content

Instantly share code, notes, and snippets.

@jammy-dodgers
Last active September 2, 2020 09:58
Show Gist options
  • Save jammy-dodgers/c9ffce1de8efeff767a84027bb34e5f1 to your computer and use it in GitHub Desktop.
Save jammy-dodgers/c9ffce1de8efeff767a84027bb34e5f1 to your computer and use it in GitHub Desktop.
C enumerator/generator; messing about with C macros - see macro expansion here: https://gist.github.com/jammy-dodgers/521e0e41ad8e042d19412a39484a2dcb
#include <stdio.h>
#define foreach(GENERATOR_TYPE, GENERATOR, LOOP_VAL, BODY) { struct GENERATOR_TYPE foreach_loop_var; foreach_loop_var = GENERATOR; \
while (GENERATOR_TYPE ## _has_next(&foreach_loop_var)) { LOOP_VAL = foreach_loop_var.current; BODY }}
#define yield(NUM, VAR) vars->current = (VAR); vars->pos = NUM; return 1; case NUM:;
#define generator(GEN_TYPE, GEN_NAME, LOCALS, BODY) struct GEN_NAME { int pos; int current; LOCALS}; \
struct GEN_NAME new_ ## GEN_NAME() {struct GEN_NAME gener_temp_init_var; gener_temp_init_var.pos = 0; return gener_temp_init_var;} \
int GEN_NAME ## _has_next(struct GEN_NAME * vars) { switch(vars->pos) { case 0: BODY; return 0; } }
generator(int, Fibonacci, int n1; int n2;, {
vars->n1 = 0;
vars->n2 = 1;
while (vars->n1 < 10000) {
int tmp = vars->n1;
vars->n1 = vars->n2;
vars->n2 = tmp + vars->n2;
yield(1, tmp)
}
})
int main() {
struct Fibonacci fib = new_Fibonacci();
foreach(Fibonacci, fib, int i, {
printf("%d\n", i);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment