I am trying to implement basic cons, car and cdr of SCHEME in C. I have made a simple program that allows me to cons two integers as shown in the main program. However, I want my program to be able to cons a 'consed object' with a digit as well as cons a 'consed object' with another 'consed object' as shows below:
- (cons 2 3)
- (cons 2 (cons 2 3))
- (cons (cons 2 3) (cons 2 3))
Since the limitation arises because the data in the struct is of type int, is it possible to have a variable accept multiple data types in C? If yes, how? If not, is there another way to deal with this issue? Here is my code:
#include <stdio.h>
#include <string.h>
typedef struct cons_object {
int data;
struct node* next;
} cons_object;
cons_object* cons(int x, int y )
{
cons_object* car = NULL;
cons_object* cdr = NULL;
car = malloc(sizeof(struct cons_object));
cdr = malloc(sizeof(struct cons_object));
car->data = x;
car->next = cdr;
cdr->data = y;
cdr->next = NULL;
return car; /*returns the pointer car*/
}
int car(cons_object* list) /*takes in a consed object*/
{
cons_object* car = list;
int y;
y = car->data;
return y;
}
int cdr(cons_object* list)
{
cons_object* cdr = list;
cdr = cdr->next;
int z;
z= cdr->data;
return z;
}
int main ()
{
int y = car (cons(33,42));
printf("%d\n",y);
int z = cdr (cons(3,4));
printf("%d\n",z);
return 0;
}