October 28, 2017
---------------------------------------------------------------
In a reddit thread I saw a post, part of which dealt with a
stack reordering from this:
abc
into this:
bbaca
The solution, with commentary was:
Start
P: a b c
R:
Push to R, ">r"
P: a b
R: c
Duplicate top of P, "dup"
P: a b b
R: c
Rotate third element to top of P, "rot"
P: b b a
R: c
Pop from R, "r>"
P: b b a c
R:
Copy second element over the first, "over"
P: b b a c a
R:
Result:
>r dup rot r> over
While this is certainly a workable solution, I take a more pragmatic
view. If it's not something that'll benefit from a set of lower level
transformations (in terms of code space on embedded targets, or time
[if run repeatedly]), why go through the hassle?
I implemented `reorder` in RETRO to handle transformations like this
in a very simple manner:
'abc 'bbaca reorder
And it's done. Works at both the interpreter and in a definition;
is easily understood. While I know Forth (after over a decade and a
half of use), I still need a few moments to go from "abc" to "bbaca"
when following the logic of ">r dup rot r> over". My `reorder` word
is less elegant than a proper stack reshuffle, but far easier for
me to work with and maintain.