begin-while-repeat

Pascal Cuoq - 14th Aug 2011

A little while ago, I was commenting somewhere that Forth had the ultimate control structure, the BEGIN (1) WHILE (2) REPEAT construction.

(1) and (2) are holes to be filled with programs. WHILE takes an evaluated condition from the stack, so that (1) can usually be divided into (1a): do some stuff and (1b): determine whether the loop should exit. Regardless of the value of the condition, (2) is run, and then, if the condition was true, REPEAT sends control back to BEGIN, and if it was false, it continues with the rest of the program.

Sometimes you need the full power of the begin-while-repeat. Not coincidentally (because this structure is really useful), this happened to us recently, so we looked for the first time at how to write begin-while-repeat in OCaml. OCaml has only while (e1) do (e2) done, but you can nest expressions arbitrarily. It turns out that the answer is:

while (1a) ; let cond = (1b) in (2) ; cond do () done 

One tiny issue is that the OCaml mode for Emacs does not seem to do a very good job of indenting it. What a shame, such a useful idiom.

Pascal Cuoq
14th Aug 2011