From 13734ef16baf54055d296416dc43da9e9b149042 Mon Sep 17 00:00:00 2001 From: hellerve Date: Thu, 7 Sep 2017 17:57:27 +0200 Subject: [PATCH] prelude: slimmed and prettified --- assets/prelude.h | 94 +++++++++++++++++++----------------------------- 1 file changed, 36 insertions(+), 58 deletions(-) diff --git a/assets/prelude.h b/assets/prelude.h index 41d4091..775ab54 100644 --- a/assets/prelude.h +++ b/assets/prelude.h @@ -1,12 +1,12 @@ #include #include +#include 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); }