prelude: slimmed and prettified

This commit is contained in:
2017-09-07 17:57:27 +02:00
parent e51ab74d28
commit 13734ef16b

View File

@@ -1,12 +1,12 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct Int;
struct String;
struct Closure;
union Value;
enum Tag { VOID, INT, STRING, CLOSURE, CELL, ENV };
enum Tag { INT, FLOAT, STRING };
typedef union Value (*Lambda)() ;
@@ -15,50 +15,36 @@ struct Int {
int value;
};
struct Float {
enum Tag t;
float value;
};
struct String {
enum Tag t;
char* value;
};
struct Closure {
enum Tag t;
Lambda lam;
void* env;
} ;
struct Env {
enum Tag t;
void* env;
};
struct Cell {
enum Tag t;
union Value* addr;
} ;
union Value {
enum Tag t;
struct Int z;
struct Int i;
struct Float f;
struct String s;
struct Closure clo;
struct Env env;
struct Cell cell;
} ;
typedef union Value Value;
static Value MakeClosure(Lambda lam, Value env) {
static Value MakeInt(int n) {
Value v;
v.clo.t = CLOSURE;
v.clo.lam = lam;
v.clo.env = env.env.env;
v.i.t = INT;
v.i.value = n;
return v;
}
static Value MakeInt(int n) {
static Value MakeFloat(float n) {
Value v;
v.z.t = INT;
v.z.value = n;
v.f.t = FLOAT;
v.f.value = n;
return v;
}
@@ -69,48 +55,40 @@ static Value MakeString(char* s) {
return v;
}
static Value MakePrimitive(Lambda prim) {
Value v;
v.clo.t = CLOSURE;
v.clo.lam = prim;
v.clo.env = NULL;
return v;
}
static Value MakeEnv(void* env) {
Value v;
v.env.t = ENV;
v.env.env = env;
return v;
}
static Value NewCell(Value initialValue) {
Value v;
v.cell.t = CELL;
v.cell.addr = malloc(sizeof(Value));
*v.cell.addr = initialValue;
return v;
}
Value sum(Value a, Value b) {
return MakeInt(a.z.value + b.z.value);
return MakeInt(a.i.value + b.i.value);
}
Value product(Value a, Value b) {
return MakeInt(a.z.value * b.z.value);
return MakeInt(a.i.value * b.i.value);
}
Value difference(Value a, Value b) {
return MakeInt(a.z.value - b.z.value);
return MakeInt(a.i.value - b.i.value);
}
Value display(Value v) {
printf("%i\n",v.z.value);
switch(v.t) {
case INT:
printf("%d\n",v.i.value);
break;
case FLOAT:
printf("%f\n",v.f.value);
break;
case STRING:
printf("%s\n",v.s.value);
break;
}
return v;
}
Value equal(Value a, Value b) {
return MakeInt(a.z.value == b.z.value);
if (a.t != b.t) return MakeInt(1);
switch(a.t) {
case INT: return MakeInt(a.i.value == b.i.value);
case FLOAT: return MakeInt(a.f.value == b.f.value);
case STRING: return MakeInt(!strcmp(a.s.value, b.s.value));
}
return MakeInt(0);
}