J
Jack Trades
I'm trying to learn C by writing an interpreter for a Scheme-like
language in it. I have the following struct which is used for Scheme
objects...
typedef struct object {
object_type type;
union {
struct { // FIXNUM
long value;
} fixnum;
struct { // FLONUM
double value;
} flonum;
// Other types omitted
} data;
} object;
When I tried to implement + I couldn't figure out how to do it simply
and ended up writing this...
object *h_numeric_add(object *obj_1, object *obj_2) {
switch (obj_1->type) {
case FLONUM:
switch (obj_2->type) {
case FLONUM:
return make_flonum(obj_1->data.flonum.value +
obj_2->data.flonum.value);
case FIXNUM:
return make_flonum(obj_1->data.flonum.value +
obj_2->data.fixnum.value);
}
case FIXNUM:
switch (obj_2->type) {
case FLONUM:
return make_flonum(obj_1->data.fixnum.value +
obj_2->data.flonum.value);
case FIXNUM:
return make_fixnum(obj_1->data.fixnum.value +
obj_2->data.fixnum.value);
}
}
}
It works just fine but looks very ugly to me, especially considering
that the only thing I'm varying is the obj->data.flo/fixnum.value. Is
there a better way to do this?
Thanks
Jack Trades
language in it. I have the following struct which is used for Scheme
objects...
typedef struct object {
object_type type;
union {
struct { // FIXNUM
long value;
} fixnum;
struct { // FLONUM
double value;
} flonum;
// Other types omitted
} data;
} object;
When I tried to implement + I couldn't figure out how to do it simply
and ended up writing this...
object *h_numeric_add(object *obj_1, object *obj_2) {
switch (obj_1->type) {
case FLONUM:
switch (obj_2->type) {
case FLONUM:
return make_flonum(obj_1->data.flonum.value +
obj_2->data.flonum.value);
case FIXNUM:
return make_flonum(obj_1->data.flonum.value +
obj_2->data.fixnum.value);
}
case FIXNUM:
switch (obj_2->type) {
case FLONUM:
return make_flonum(obj_1->data.fixnum.value +
obj_2->data.flonum.value);
case FIXNUM:
return make_fixnum(obj_1->data.fixnum.value +
obj_2->data.fixnum.value);
}
}
}
It works just fine but looks very ugly to me, especially considering
that the only thing I'm varying is the obj->data.flo/fixnum.value. Is
there a better way to do this?
Thanks
Jack Trades