SICP/shared/scm2c/datum.c

88 lines
1.7 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include "datum.h"
datum* cons(datum *e, datum *xs) {
e->next = xs;
return e;
}
datum* const_i32(int32_t value) {
datum* r = malloc(sizeof(datum));
if (!r) exit(-1);
r->type = datum_type_i32;
r->value = value;
return r;
}
datum* const_bool(int32_t value) {
datum* r = malloc(sizeof(datum));
if (!r) exit(-1);
r->type = datum_type_bool;
r->value = value;
return r;
}
datum* const_primitive_proc(datum* (*primitive_procedure) (datum*)) {
datum* r = malloc(sizeof(datum));
if (!r) exit(-1);
r->type = datum_type_primitive_proc;
r->primitive_procedure = primitive_procedure;
return r;
}
int primitive_procedure(datum* d) {
if (d->type == datum_type_primitive_proc) {
return 1;
}
return 0;
}
int is_false(datum *d) {
if (d->type == datum_type_i32) {
return 0;
} else if (d->type == datum_type_bool) {
return !d->value;
} else if (d->next) {
return 0;
} else {
return 1;
}
}
int datum_eq(datum *a, datum *b) {
if ((a->type == datum_type_i32) && (b->type == datum_type_i32)) {
return a->value == b->value;
}
return 0;
}
int datum_lt(datum *a, datum *b) {
if ((a->type == datum_type_i32) && (b->type == datum_type_i32)) {
return a->value < b->value;
}
return 0;
}
void print_datum(datum* d) {
if (!d) {
printf("ERROR - DATUM is null");
exit(-1);
}
switch (d->type) {
case datum_type_i32:
printf("%i", d->value);
break;
default:
printf("Cannot print type %u", d->type);
break;
}
}
void* compiled_procedure_entry(datum* d) {
return d->compiled_procedure_entry;
}