Skip to content

Instantly share code, notes, and snippets.

@forestbelton
Created April 6, 2013 03:41
Show Gist options
  • Save forestbelton/5324658 to your computer and use it in GitHub Desktop.
Save forestbelton/5324658 to your computer and use it in GitHub Desktop.
LISP-like list macros for C
#include <assert.h>
#include <stdlib.h>
#define LIST(a) struct { \
a v; \
void *n; \
}
#define CAR(xs) xs->v
#define CDR(xs) xs->n
#define CONS(a, x) do { \
void *t = x; \
x = malloc(sizeof *x); \
\
assert(x != NULL); \
x->v = a; \
x->n = t; \
} while(0)
#define MAP(f, x) do { \
void *t = x; \
\
while(x != NULL) { \
CAR(x) = f(CAR(x)); \
x = CDR(x); \
} \
\
if(t) x = t; \
} while(0)
#include <stdio.h>
int times2(int x) { return x * 2; }
int main() {
int i;
LIST(int) *xs = NULL;
for(i = 10; i > 0; --i)
CONS(i, xs);
MAP(times2, xs);
while(xs != NULL) {
printf("%d -> ", CAR(xs));
xs = CDR(xs);
}
printf("nil\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment