Singly-linked list/Element definition: Difference between revisions

Content added Content deleted
m (→‎[[E]]: Split off Forth section)
Line 85: Line 85:
==[[Forth]]==
==[[Forth]]==
[[Category:Forth]]
[[Category:Forth]]

Forth has no "struct" facility, but you can easily implement a single linked list with a data cell using a double-cell value.

: >cell-link ( a -- a ) ;
: >cell-data ( a -- b ) cell+ ;

As an example of usage, here is a word to link 'a' after 'b'

: chain ( a b -- ) \ links 'a' after 'b'
over >r
dup >cell-link @ r> >cell-link ! \ a points at b's old link
>cell-link ! ;

Or with named parameters:

: chain { a b -- }
b >cell-link @ a >cell-link !
a b >cell-link ! ;

Due to Forth's lack of typechecking, 'b' in the above examples does not have to be an actual cell, but can instead be the head pointer of the list.