Skip to content

Instantly share code, notes, and snippets.

@jonsterling
Created February 15, 2012 15:53
Show Gist options
  • Select an option

  • Save jonsterling/1836841 to your computer and use it in GitHub Desktop.

Select an option

Save jonsterling/1836841 to your computer and use it in GitHub Desktop.
Algebraic Data Types in C: Example Output
-- ADTs are declared with a Haskell-like syntax.
data Expr = Plus { l :: int, r :: int }
| Times { l :: int, r :: int }
| Inc {o :: int}
| Dec {o :: int}
// This is the output of my ADT preprocessor
struct Expr {
enum {Plus,Times,Inc,Dec} tag;
union {
struct {
int l;
int r;
} Plus;
struct {
int l;
int r;
} Times;
struct {
int o;
} Inc;
struct {
int o;
} Dec;
};
};
static const struct {
struct Expr (^Plus)(int l
,int r);
struct Expr (^Times)(int l
,int r);
struct Expr (^Inc)(int o);
struct Expr (^Dec)(int o);
} Expr = {
.Plus = ^(int l,int r){
struct Expr x = {Plus};
x.Plus.l = l;
x.Plus.r = r;
return x;
},
.Times = ^(int l,int r){
struct Expr x = {Times};
x.Times.l = l;
x.Times.r = r;
return x;
},
.Inc = ^(int o){
struct Expr x = {Inc};
x.Inc.o = o;
return x;
},
.Dec = ^(int o){
struct Expr x = {Dec};
x.Dec.o = o;
return x;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment