如果它们是整数,如何在此代码中打印汽车和cdr以获取consed对象?

时间:2013-07-24 17:38:31

标签: c mit-scheme

我正在尝试构建一个在c中实现scheme的交叉编译器。为此,我试图使用cons和列表实现基本的方案结构。下面显示的代码用于缺点。当它是一个整数而不是另一个consed对象时,我无法访问一个consed对象的汽车。

#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;
}

1 个答案:

答案 0 :(得分:0)

eval_cons(cons(3,4));

也许,应该是

cons_object a = { NUMBER, .data.i = 3};
cons_object b = { NUMBER, .data.i = 4};
eval_cons(cons(&a, &b));

int a;
a = first->data.i;//also second
printf("%d ",a);