can read and print doubles

This commit is contained in:
Erik Svedäng 2016-03-17 12:20:53 +01:00
parent 39cb5b4291
commit 4c58b42c7e
4 changed files with 30 additions and 2 deletions

View File

@ -41,6 +41,12 @@ Obj *obj_new_float(float x) {
return o;
}
Obj *obj_new_double(double x) {
Obj *o = obj_new('W');
o->f64 = x;
return o;
}
Obj *obj_new_string(char *s) {
Obj *o = obj_new('S');
o->s = strdup(s);

View File

@ -89,6 +89,8 @@ typedef struct Obj {
void *void_ptr;
// Float
float f32;
// Double
double f64;
// Char
char character;
// Bool
@ -108,6 +110,7 @@ typedef Obj* (*Primop)(Obj**, int);
Obj *obj_new_cons(Obj *car, Obj *cdr);
Obj *obj_new_int(int i);
Obj *obj_new_float(float x);
Obj *obj_new_double(double x);
Obj *obj_new_string(char *s);
Obj *obj_new_symbol(char *s);
Obj *obj_new_keyword(char *s);

View File

@ -207,6 +207,12 @@ void obj_to_string_internal(Obj *total, const Obj *o, bool prn, int indent) {
snprintf(temp, 64, "%f", o->f32);
obj_string_mut_append(total, temp);
}
else if(o->tag == 'W') {
static char temp[64];
snprintf(temp, 64, "%f", o->f64);
obj_string_mut_append(total, temp);
obj_string_mut_append(total, "d");
}
else if(o->tag == 'S') {
if(prn) {
obj_string_mut_append(total, "\"");

View File

@ -190,6 +190,7 @@ Obj *read_internal(Obj *env, char *s, Obj *filename) {
read_pos++;
}
bool is_floating = false;
bool is_double = false;
char scratch[32];
int i = 0;
while(isdigit(CURRENT)) {
@ -205,14 +206,26 @@ Obj *read_internal(Obj *env, char *s, Obj *filename) {
read_pos++;
break;
}
if(CURRENT == 'd') {
is_double = true;
read_pos++;
break;
}
}
scratch[i] = '\0';
if(is_floating) {
if(is_double) {
double x = atof(scratch) * negator;
Obj *new_double = obj_new_double(x);
obj_set_line_info(new_double, line, pos, filename);
return new_double;
}
else if(is_floating) {
float x = (float)atof(scratch) * negator;
Obj *new_float = obj_new_float(x);
obj_set_line_info(new_float, line, pos, filename);
return new_float;
} else {
}
else {
int num = atoi(scratch) * negator;
Obj *new_int = obj_new_int(num);
obj_set_line_info(new_int, line, pos, filename);