Skip to content

Instantly share code, notes, and snippets.

@buptpatriot
Last active January 1, 2016 07:49
Show Gist options
  • Save buptpatriot/8113659 to your computer and use it in GitHub Desktop.
Save buptpatriot/8113659 to your computer and use it in GitHub Desktop.
Pair object just like that in lisp.
#include <stdio.h>
#include <stdlib.h>
typedef enum {
OBJ_INT,
OBJ_PAIR
} ObjectType;
typedef struct sObject {
ObjectType type;
union {
int value;
struct {
struct sObject* head;
struct sObject* tail;
};
};
} Object;
void objectPrint(Object* object) {
switch (object->type) {
case OBJ_INT:
printf("%d", object->value);
break;
case OBJ_PAIR:
printf("(");
objectPrint(object->head);
printf(" . ");
objectPrint(object->tail);
printf(")");
break;
}
}
Object* newIntObject(int value) {
Object* object = malloc(sizeof(Object));
object->type = OBJ_INT;
object->value = value;
return object;
}
Object* newPairObject(Object* head, Object* tail) {
Object* object = malloc(sizeof(Object));
object->type = OBJ_PAIR;
object->head = head;
object->tail = tail;
return object;
}
Object* cons(Object* head, Object* tail) {
return newPairObject(head, tail);
}
Object* car(Object* object) {
switch (object->type) {
case OBJ_INT:
return NULL;
case OBJ_PAIR:
return object->head;
}
}
Object* cdr(Object* object) {
switch (object->type) {
case OBJ_INT:
return NULL;
case OBJ_PAIR:
return object->tail;
}
}
int main(int argc, const char * argv[]) {
Object* intObject1 = newIntObject(1);
Object* intObject2 = newIntObject(2);
Object* pairObject1 = newPairObject(intObject1, intObject2);
objectPrint(pairObject1);
printf("\n");
Object* pairObject2 = cons(intObject1, pairObject1);
objectPrint(pairObject2);
printf("\n");
Object* object = car(cdr(pairObject2));
objectPrint(object);
printf("\n");
free(intObject1);
free(intObject2);
free(pairObject1);
free(pairObject2);
free(object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment