Last active
April 11, 2023 06:21
-
-
Save niconii/2e2857fb062f46abc164a2cb73db782b to your computer and use it in GitHub Desktop.
Simple linked list implementation in Forth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
0 constant nil | |
: cons ( car cdr -- list ) here >r swap , , r> ; | |
: list ( x... #x -- list ) nil swap 0 ?do cons loop ; | |
: list: ( x... #x "name" -- ) list constant ; | |
: car ( list -- car ) @ ; | |
: car! ( car list -- ) ! ; | |
: cdr ( list -- cdr ) cell+ @ ; | |
: cdr! ( cdr list -- ) cell+ ! ; | |
: list. ( list -- ) begin ?dup while dup car . cdr repeat ; | |
: >end ( list -- end ) begin dup cdr while cdr repeat ; | |
: append ( l1 l2 -- list ) over >end cdr! ; | |
( Example usage ) | |
100 200 300 3 list: foo | |
foo car . \ prints "100 " | |
foo cdr car . \ prints "200 " | |
foo cdr cdr car . \ prints "300 " | |
foo list. \ prints "100 200 300 " | |
400 500 2 list: bar | |
foo bar append list. \ prints "100 200 300 400 500 " | |
foo list. \ prints "100 200 300 400 500 " | |
bar list. \ prints "400 500 " | |
600 700 800 3 list: baz | |
baz bar append list. \ prints "600 700 800 400 500 " | |
444 bar car! | |
bar list. \ prints "444 500 " | |
foo list. \ prints "100 200 300 444 500 " | |
baz list. \ prints "600 700 800 444 500 " |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment