[Previous] Lesson 2 [Next]

Procedures and Control Flow

A Simple Procedure

Although TLWNN is an imperative programming language, it has no built-in control flow facilities of the kind found in most imperative languages.  However, it does have a powerful system of procedures, which can be used to simulate most structured programming constructs.  Like TLWNN and everything else in it, procedures have no names.  They are stored on the stack, in the same way as numbers are.

Example four
Hello world five times
[72! 101! 108*!! 111! 44! 32! 119! 111! 114! 108! 100! 33! 10!]
****!!!!!

The symbols [ and ] delimit a procedure.  This procedure is put on the stack.  It is then duplicated four times, and then each copy is executed (this is another use of !).

A similar example is this:

Example five
Compositional text output
[76!111!114!100!44!32!104!97!118!101!32!109!101!114!99!121!10!]*!
67!104!114!105!115!116!44!32!104!97!118!101!32!109!101!114!99!121!10!
!

which will print these lines familiar to most Christians:

Lord, have mercy
Christ, have mercy
Lord, have mercy

Looping Forever

Of course, the above code is only any good if we want to repeat something a finite number of times.  If we want an infinite loop, we must somehow make the procedure call itself.  However, in the absence of names, we can't use recursion in the usual manner.  However, what we can do is give the procedure a copy of itself to call.

Example six
Hello world infinite loop
[72! 101! 108*!! 111! 44! 32! 119! 111! 114! 108! 100! 33! 10! *!]
*!

This is similar to the technique for simulating recursion in languages such as Unlambda.  The procedure is put on the stack and then duplicated.  Upon execution, the procedure duplicates its original that was just below it in the stack, and then runs the copy it's just created.  And so it continues....