Iteration and Repetition
Performing the same task for each item in a list, or over and over again.
Some tasks need to be carried out for every item in a collection. An action for each machine, done once for each user in a list, or perhaps once for each component in a larger system. Other tasks happen over and over again.
These iterating and looping behaviours are supported by control structures built into Technique as keywords. Consider an evening at a restaurant at the End of the Universe. A single sitting looks something like this:
sitting :
1. Welcome the party
2. Take orders
3. Serve dinner
4. Watch the Universe End
5. Settle the bill
Iterating over a collection
But taking orders really means taking an order from each guest. Likewise
when it comes time to serve the meal, their dishes are given to each person
in turn. That iteration across a collection is what the
{ foreach }
keyword is for:
sitting :
1. Welcome the party
2. Take orders
{ foreach guest in party }
a. Recommend the Dish of the Day
b. Note their selection
3. Serve dinner
{ foreach guest in party }
a. Bring the entrée
b. Bring the main course
c. Bring dessert
4. Watch the Universe End
5. Settle the bill
The { foreach }
code block creates a scope which is
to be carried out once for every value in the collection, with { guest }
bound to the current value while the substeps
are performed.
Use iteration when you have a list of items and a task to do for each element.
Repeating an action
Now consider time. Milliways isn't open for one evening—it opens every evening back at the same point. The procedure that matters isn't a single sitting but the indefinite sequence of them:
operate_restaurant :
1. Open the doors
2. { repeat <sitting> }
The { repeat }
keyword runs the subsequent expression
and then runs it again, and so on. There is no list to iterate; the invocation
of the sitting :
procedure shown here just repeats
over and over.
The reason these control structures are expressions is that the language needed
a way to tell the difference between a keyword and the same word being used in
a content sentence. You'll need to repeat
that because the factory is very loud is a valid description. To make
it clear that the repeat is actually specifying the looping control
structure it appears as { repeat }
in an inline code
block instead.
Use repetition when the work is genuinely cyclical: running health checks, servicing requests, or operating a restaurant whose punctual arrival each evening can always be relied upon.