This is a program to illustrate where nested procedures are of use but especially where two different procedures exist at once with the same code body. They are objects implemented as procedures.

This short program needs a long explanation. Here are variants in several languages: Algol 68, GNU C, Scheme and JavaScript. The purpose is to find when a finite state machine (here a := a*23 mod 1000) loops. The trick (by Floyd, I think) is to make two instances and cycle one twice as fast as the other. After both have begun to loop, they will collide. In more complex state machines it is convenient to write the state transition rules using variables without subscripts which might otherwise be used to discriminate among several instances of the machine. Here both of the first two invocations of the recursive routine r produce a machine instance and records a routine to step that machine and return its state.

The hack is to run the double instance algorithm while the two abstracted instances are each separately on the stack. After the answer is reported we are done with the machines and the stack dissolves.

Pascal and PL/I would do this nicely too. This can be done in Java and C++ but only in a different style. Here is another application.