What general tips do you have for golfing in Forth (and its clones)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Forth (e.g. "remove comments" is not an answer).
Avoid explicit loops at all costs
Forth has two looping constructs,
x y do ...
loop, and lesser known
[until] x y where
y are values for limit and index, or conditions to be noted, respectively.
These are very slow, very wordy (haha) and overall rather bloaty, so only use them if you need to.
Instead, like a proper functional language (which Forth is, really), one should prefer recursivity over explicit loops because it tends to be shorter and makes a better use of the language.
Forth has a lot of cool builtin words, many of which are helpful for crafting the sorts of algorithms found on PPCG.
A bad but illustrative example of this are the words for increment (
1+) and decrement (
1-). They save a byte over writing
1 + to increment the top of the stack.
Additonally, here is a handy list of many (probably not all) words found in modern distributions like
Watch the stack
When writing your code, pay attention to what happens on the stack at each command. I usually draw it out as I go, like so:
6 6 7 7 6 * DUP 42 42
As you go like this, you may find it easier to recognize when you can make use of stack operations like
Leave the junk
Programs aren't required to be stack-safe.
Instead, they can leave extra junk on the stack if it saves you bytes. In Forth, the "return value" is leaving something on top of the stack. It probably doesn't matter what junk you have below that on the stack unless you're using recursion and stack depth matters.