I am trying to build a cross compiler that implements scheme in c. For this I am trying to implement the basic scheme structure using cons and lists. The code which is shown below is for cons. I am not able to access the car of a consed object when it's an integer and not another consed object.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef enum
{PAIR, NUMBER} object;
typedef struct node cons_object;
struct node {
object type;
union
{
int i;
float f;
char* string;
struct pair {
cons_object* car;
cons_object* cdr;
} pair;
} data;
};
cons_object* cons(cons_object* x, cons_object* y)
{
cons_object* obj;
obj = malloc(sizeof(cons_object*));
obj->type = PAIR;
obj->data.pair.car = x;
obj->data.pair.cdr = y;
return obj; /*returns the pointer car*/
}
cons_object* car(cons_object* list) /*takes in a consed object*/
{
cons_object* y;
y = list->data.pair.car;
return y; /* returns the pointer of another consed object */
}
cons_object* cdr(cons_object* list)
{
cons_object* z;
z = list->data.pair.cdr;
return z; /* returns the pointer of another consed object */
}
void eval_cons(cons_object* pair)
{
cons_object* first;
cons_object* second;
int *a; /* An integer type pointer to dereference the values returned by car and cdr pointers */
first = car(pair);
second = cdr(pair);
{
if(first->type == PAIR){
eval_cons(first); // If car is a cons-ed object, it is again sent to the eval function
}
else
{
a = (int *)&first; /* tried type casting too */
printf("%d",*a);
}
}
if(second->type == PAIR)
eval_cons(second); // If cdr is a cons-ed object, it is again sent to the eval function
else
{
a = (int *)&second;
printf("%d",*a); // prints the dereferenced value
}
}
// If eval starts working then we could test it from the following sample code:
int main ()
{
eval_cons(cons(3,4)); /* cant find a way to access 3 and 4 */
getchar();
return 0;
}