Lists
Added 31 Jul 2008
Recall the traditional list code snippets, as given in class:
-
The list type:
struct AList {
int first;
struct AList * rest;
};
typedef struct AList * List;
My style of hiding the fact that
Listis pointer is based on what you're familiar with from Scheme and Java. Others prefer something liketypedef struct AList Cons;In your own code, you may do what you wish. -
To create a list:
List make_empty()
{
return NULL;
}
List make_cons(int first, List rest)
{
List list = (List) malloc(sizeof(struct AList));
if (list == NULL) {
fprintf(stderr,"Out of memory.\n");
exit(1);
}
list->first = first;
list->rest = rest;
return list;
}
-
To access a list:
List list = ...;
if (list == NULL) {
...
}
else {
...list->first ... list->rest ...
}