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. The precise implementation of execution tokens in your forth interpreter might make things simpler than shown:
: offset r> + >r ;
: b dup . 1+ ;
: a dup offset b b b b b b b b b b drop ;
1 a cr 3 a cr 8 a cr
Which prints:
1 2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
8 9
Another fun trick is rewriting the return stack. This program does exactly the same thing as the abovefirst example:
: 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.