2 ms·
Though uLisp has tail-call optimization, if the C compiler doesn't, then the garbage collector needs stack in proportion to list length: void markobject (obj
by kazinator 10y ago
Though uLisp has tail-call optimization, if the C compiler doesn't, then the garbage collector needs stack in proportion to list length:
void markobject (object *obj) {
if (obj == NULL) return;
object* arg = car(obj);
if (marked(obj)) return;
int type = obj->type;
mark(obj);
if (type != SYMBOL && type != NUMBER) { // cons
markobject(arg);
markobject(cdr(obj)); // <--- TAIL CALL!
}
}
It's simple enough to obj = cdr(obj) and wrap a loop around this.
- johnsondavies 10y agoGood suggestion!
- kazinator 10y agoBy the way, you can't eliminate the need for a stack when traversing the cell graph (unless you give them parent pointers, thereby hiding the stack in the data). That's why I wrote "in proportion to list length", not "tree structure depth" in general. Above, we still have recursion when marking the arg = car(obj) value. However, Lisp lists tend to be greatly unbalanced in favor of growing in the cdr direction; that is why it helps to iterate on the cdr.