Memory manipulation
Here are words that move and sort data in local RAM.
move
Moves data from source to destination.
- move dsn for a! @+ a push a! !+ a pop next drop drop ;
This is the best code if data won't overlap or if destination is not greater than source. The strategy is to increment both source and destination in register a
- Fetch word from source
- Save incremented a on return stack
- Store to destination
- Restore addresses and repeat
- Discard addresses
+move
Moves data from source to destination when data overlap and destination is greater than source. As in pushing an entry into a table. The count is n-1, which is convenient.
- +move dsn dup push . + a! pop dup push . + a
begin a! @ a -1 . + push a! ! a -1 . + pop next drop drop ;
Clearly the code for move is shorter and faster.
The first line moves source and destination to the end of their regions. It is unnecessary if they already point there.
- Push count onto return stack for begin
- Add count to source and save in a (convenient that it's n-1)
- Retrieve count (pop dup push) and add to destination
- Restore source
- Start loop
- Fetch from source
- Decrement address and save on return stack
- Store to destination
- Decrement address and restore source
- Repeat
- Discard addresses
bubble
This bubble sort takes an entry at the beginning of a sorted table and finds its place. The table must have a stopper greater than any possible entry. This is the smallest (only) sort I know.
- bubble nt a! for @+ @ - + - -if
@ a -1 + a! @ push !+ pop ! then drop next ;
The two adds do not need a dot before them because they're in slot 3.
- Set a and start loop
- Subtract entry from its successor
- If not possible (negative) entries must be exchanged
- Fetch the second
- Decrement a
- Fetch the first and save on return stack
- Store the second
- Restore and store the first
- Drop the result of subtract
- Repeat
Looks like building this table should start from high address and grow toward lower.