Loop structures: Difference between revisions

Line 231:
===Looping===
Most looping is done with recursion. Tail recursion is properly optimized.
<syntaxhighlight lang="factor">
: forever ( quot -- ) dup slip forever ; inline
[ "A hungry raptor stalks you..." print flush 2000 random sleep ] forever
</syntaxhighlight>
 
===Iteration===
<syntaxhighlight lang="factor">
Most indices are implicit or not present at all.
3 [ "pint" drink ] times
{ "high" "level" "language" } [ print ] each
high
level
language
10 [ sq ] map
{ 0 1 4 9 16 25 36 49 64 81 }
{ 1 2 3 } { 4 5 6 } [ * ] 2map .
{ 4 10 18 }
10 [ even? ] subset .
V{ 0 2 4 6 8 }
0 10 3 <range> >array .
{ 0 3 6 9 }
10 1 -2 <range> >array .
{ 10 8 6 4 2 }
2222 [ dup 0 > ] [ 2/ dup ] [ ] unfold nip .
{ 1111 555 277 138 69 34 17 8 4 2 1 0 }a
</syntaxhighlight>
 
Iterating with an index:
<syntaxhighlight lang="factor">
: indexed-alphabet. ( -- )
"abcdefghijklmnopqrstuvwxyz"
[ [ 1string ] [ number>string ] bi* ": " glue print ] each-index ;
</syntaxhighlight>
 
==[[Forth]]==
===DO-LOOP===