c でスキームを実装するクロス コンパイラを構築しようとしています。このために、コンスとリストを使用して基本的なスキーム構造を実装しようとしています。以下に示すコードは短所用です。consed オブジェクトが整数であり、別の consed オブジェクトではない場合、consed オブジェクトの car にアクセスできません。
#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;
}