Cons cell implementation
By Chris Walton
\ Cons cells a.k.a. linked lists \ by Chris Walton \ \ Cons cells have two items. car is the first, cdr, the second. \ Use cxr! to store to a cell, cxr@ to read from it. \ cons returns the address of a newly created cons cell from 2 cells given \ cons0 as above, but uses 0 instead of given arguments. \ \ Linked lists can be made by having first item be data, second link to next. \ Double linked lists will have a link to a cell in cdr describing \ both previous and next. \ This thing is infinetely extendable - use it to your advantage. \ \ Compatibility: \ Works fine with any ANS forth. \ Doesn't work with PygmyForth. \ Might work with IsForth, haven't tried. \ Don't know about other Forths \ \ If your forth doesn't support any of the following, uncomment them. \ : throw drop ; \ : tuck swap over ; : car! ( v a - ) ! ; : cdr! ( v a - ) cell+ ! ; : car@ ( a - v ) @ ; : cdr@ ( a - v ) cell+ @ ; : cons ( k v - a ) swap 2 cells allocate throw tuck ! tuck ! ; : cons0 ( - a ) 0 0 cons ;
A simple cons cell can be done with less complexity (no dynamic memory allocation): :-)
\ \ Simplified cons cells \ Tested under RetroForth, gForth, Win32Forth \ : car! ( v a -- ) ! ; : cdr! ( v a -- ) cell+ ! ; : car@ ( a -- v ) @ ; : cdr@ ( a -- v ) cell+ @ ; : cons ( car cdr -- a ) swap here >r , , r> ; : cons0 ( -- a ) 0 0 cons ; \ For Retro 11.x \ Use @car @cdr !car !cdr with this. : car ( a-A ) ; : cdr ( a-A ) 1+ ; : cons ( cc-a ) swap here [ 2, ] dip ; : cons0 ( -a ) 0 0 cons ; \ \ For PygmyForth \ : car! ( v a -- ) ! ; : cdr! ( v a -- ) 2 + ! ; : car@ ( a -- v ) @ ; : cdr@ ( a -- v ) 2 + @ ; : cons ( car cdr -- a ) SWAP HERE PUSH , , POP ; : cons0 ( -- a ) 0 0 cons ;