Looping combinators
Factor handbook > The language > Combinators

Prev:Conditional combinators
Next:Compositional combinators


In most cases, loops should be written using high-level combinators (such as Sequence combinators) or tail recursion. However, sometimes, the best way to express intent is with a loop.
while ( ..a pred: ( ..a -- ..b ? ) body: ( ..b -- ..a ) -- ..b )

until ( ..a pred: ( ..a -- ..b ? ) body: ( ..b -- ..a ) -- ..b )


To execute one iteration of a loop, use the following word:
do ( pred body -- pred body )


This word is intended as a modifier. The normal while loop never executes the body if the predicate returns false on the first iteration. To ensure the body executes at least once, use do:
[ P ] [ Q ] do while

A simpler looping combinator which executes a single quotation until it returns f:
loop ( ... pred: ( ... -- ... ? ) -- ... )