c - 如果此代码中 consed 对象的 car 和 cdr 是整数,如何打印它们?

标签 c mit-scheme

我正在尝试构建一个在 c 中实现方案的交叉编译器。为此,我尝试使用 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;
}

最佳答案

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);

关于c - 如果此代码中 consed 对象的 car 和 cdr 是整数,如何打印它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17841065/

相关文章:

c - double 的 atof 精度正在引起悲伤

macos - 如何使箭头键在MIT Scheme解释器中起作用?

mit-scheme - 如何在控制台模式下运行 Edwin 编辑器

console - 如何使用控制台作为Guile Scheme的输入和输出?

lisp - SICP 2.42 八皇后。帮忙看看我的代码有什么问题?

c - sqlite3 中的表创建不起作用

c - 使用 fgets() 终止循环

指示发生错误的通用字符

将特定数据从源缓冲区复制到多个目标缓冲区

lisp - 与 g 建立同位函数。在 mit 计划中