Skip to main content
2 of 4
added 498 characters in body
JohnE
  • 5.1k
  • 1
  • 22
  • 33

Forth

A common-enough idiom sometimes known as "factored unrolling". This program prints the numbers between 0 and 99, inclusive. The same technique can be applied to nearly any language, but forth syntax and semantics make the idiom particularly compact and convenient.

: o   dup . 1 +           ; \ ones
: t   o o o o o o o o o o ; \ tens
: h   t t t t t t t t t t ; \ hundreds
0 h drop

If you're really tricky you can compute an offset into an unrolled loop like this and produce an equivalent to Duff's Device.

Another fun trick is rewriting the return stack. This program does exactly the same thing as the above:

: rewind   dup 99 < if r> dup 1 - >r >r then ;
: main     0 rewind dup . 1 +                ;
main drop

The precise mechanics of this are highly implementation dependent, but the above seems to work on JSForth. The idea is that the call to rewind stores a position inside main on the rstack and then rewind conditionally rewrites the stack so that when main returns it returns back into main just before rewind was originally called.

JohnE
  • 5.1k
  • 1
  • 22
  • 33