In Common Lisp, you have synonyms for car and cdr called first and rest.
car and cdr are just accessors (readable and writable, although this is CL specific) for the 2 fields of the cons structure. Chains of conses make lists (proper or improper). The end of a proper list is marked by a NIL (or also known as '(), the empty list), such that the cdr (cdr points to the /rest/ of the list, while car points to the current/top element of the list) of the last cons in the list is NIL. When you're using chains of conses as lists (and for all intents and purposes, you don't need to use car/cdr to access them at all - there are more specific functions for operating on lists), it might make sense to use first/rest synonyms instead of car/cdr, so that you would be more clear that you're working on lists and not on plain conses (which are nothing more than pairs of 2 values, and can be used as such, for representing all kinds of data which fit the bill).
Name:
Anonymous2010-10-12 9:40
Better names for these would be head and tail which would be derived from the metaphor of a snake: a snake is made up of a head and the rest of body being its tail.
>>20
Just make your own structure that has as many fields as you like containing anything you want. If they had more fields, they'd be something else, and that would come with extra complexity and more code that needs to be written to accomodate that (for example, you could make a doubly linked list using a 3 field structure).
>>21
Well, yeah. >>22
Anyway I was thinking some more and with an arbitrary number of cells, it just becomes arrays of arrays. A cons cell is as simple as possible and no simpler.
You could write a doubly-linked list with two conses per value, substituting cadr for previous and cddr for next.
public final class Cons {
/** extensive javadoc omitted for brevity... */
private Object car;
private Object cdr;
public Object getFirstElementOfList() { return car; }
public Object getTailOfList() { return cdr; }
public void setFirstElementOfListBang...
ConsGetter cadr = ConsGetterFactory.makeConsGetterFromXMLString("<!DOCTYPE consgetter PUBLIC \"-//LISP//DTD CONSGETTER 1.0\" \"http://www.lisp.org/lisp/lisp/DTD/consgetter.dtd\">" +
"<consgetter> <elementgetter> <element>cdr</element> <!-- get rest of elements --> </elementgetter> <elementgetter> <element>car</element> <!-- get first element --> </elementgetter> </consgetter>");
public List(Object head) {
this.head = new Node(head);
}
public Object car() {
if (head == null)
throw new IllegalStateException();
else
return head;
}
public List cdr() {
Node newHead = new Node(this.head);
Node prev, next, newPrev, newNext;
for ( prev = this.head, next = this.head.next;
next != null;
prev = prev.next, next = next.next) {
newPrev = new Node(prev.object);
newNext = new Node(next.object);
newPrev.next = newNext;
}
return new List(newHead);
}