8
\$\begingroup\$

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).

\$\endgroup\$
3
\$\begingroup\$

Avoid explicit loops at all costs

Forth has two looping constructs, x y do ... loop, and lesser known [begin] ... [until] x y where x and 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.

\$\endgroup\$
2
\$\begingroup\$

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 gforth.

\$\endgroup\$
1
\$\begingroup\$

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 ROT, -ROT, 2DUP, 2OVER, etc...

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.