Hi readers. I have been fooling around with Forth as a way of forgetting my impending thesis project and defense. Googling around for some examples I found an implementation of a cons cell which unfortunately had an error. Here is a working cons cell.
: cons ( k v - a ) swap 2 cells allocate throw tuck ! tuck cell+ ! ;
: car! ( v a - ) ! ;
: cdr! ( v a - ) cell+ ! ;
: car@ ( a - v ) @ ;
: cdr@ ( a - v ) cell+ @ ;
: cons0 ( - a ) 0 0 cons ;
So that
5 15 cons 10 cons car@ car@ . 5
5 15 cons 10 cons car@ cdr@ . 15
5 15 cons 10 cons cdr@ . 10
Of course forth has no datatypes at all, if you really wanted a cons cell like in Lisp you would need an NIL and the only really reliable way to represent a NIL (as far as I can tell) would be to use two cells for all cons cell data, the first of which indicates a type code and the second the actual data.
Forth is Fun.