begin-while-repeat

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.

Comments

1. On Monday, August 15 2011, 00:09 by Pascal

Now that I am thinking about it, it seems a bit curious. I wouldn't be surprised to hear that I'm remembering Forth wrong from Apple II times.

2. On Monday, August 15 2011, 00:34 by Pascal

Yes, I was mis-remembering. The WHILE would send the control to the rest of the program directly if the condition was false, as shown on http://www.forth.com/starting-forth... .

3. On Monday, August 15 2011, 17:07 by rgrig

I wonder if forth got the idea from tex, or vice versa.

4. On Monday, August 15 2011, 23:36 by pascal

TeX, eh?

You have convinced me to dig up that previous conversation where I was last reminded of Forth. It was at http://blog.regehr.org/archives/536 and Bruno Martinez also pointed out this article: http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf .

I discovered it on that occasion, but I believe it is a classic of the "structured programming" debates of young computer science.

5. On Tuesday, August 16 2011, 16:24 by rgrig

Ah, yes. I read that paper of Knuth a long time ago but I forgot about it. I remember that it made me buy this T-shirt: http://www.flickr.com/photos/rgrig/...

So, in summary, Ole-Johan Dahl came up with the nice form.

I read your post because I was thinking of some related issues recently: http://rgrig.blogspot.com/2011/08/l...