Created
October 13, 2021 17:09
-
-
Save holoed/d4513dead334276cf11b5950714a8df6 to your computer and use it in GitHub Desktop.
Junior Closures Env C Hashtables
This file contains hidden or 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 <string.h> /* strcpy */ | |
#include <stdlib.h> /* malloc */ | |
#include <stdio.h> /* printf */ | |
#include "uthash.h" | |
struct closure { | |
void* fn; | |
struct BoxedValue** env; | |
}; | |
enum Tag { Bool, Int, Double, Char, String, Closure }; | |
union Value { int b; int v_1; double v_2; char v_3; char* v_4; struct closure* fn; }; | |
struct BoxedValue { | |
enum Tag tag; | |
union Value value; | |
}; | |
struct KeyValuePair { | |
char name[10]; /* key (string is WITHIN the structure) */ | |
int id; | |
UT_hash_handle hh; /* makes this structure hashable */ | |
struct BoxedValue* value; | |
}; | |
struct BoxedValue* mkBoxedValue(enum Tag tag, union Value value) { | |
struct BoxedValue * v = (struct BoxedValue *)malloc(sizeof(struct BoxedValue)); | |
v->tag = tag; | |
v->value = value; | |
return v; | |
} | |
struct BoxedValue* mkInt(int x) { | |
union Value v; | |
v.v_1 = x; | |
return mkBoxedValue(Int, v); | |
} | |
int main(int argc, char *argv[]) { | |
const char *names[] = { "numInt", "eqInt", "showInt", NULL }; | |
struct KeyValuePair *s, *tmp, *users = NULL; | |
for (int i = 0; names[i]; ++i) { | |
s = (struct KeyValuePair *)malloc(sizeof *s); | |
strcpy(s->name, names[i]); | |
s->value = mkInt(i); | |
HASH_ADD_STR(users, name, s); | |
} | |
HASH_FIND_STR(users, "eqInt", s); | |
if (s) printf("eqInt's id is %d\n", s->value->value.v_1); | |
/* free the hash table contents */ | |
HASH_ITER(hh, users, s, tmp) { | |
HASH_DEL(users, s); | |
free(s); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment