taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Exercise · Volume 1 · 1.4.2-1

Exercise 1.4.2-1

not stated yet in Lean solution written

Rating10
KindInformal: the exercise has no formal statement, so Lean does not state it from the written solution
SectionSection 1.4.2 of Volume 1. Companion chapter: Coroutines

The task

Explain why it is hard for the author of a textbook to find short, simple examples of coroutines.

The exact wording is in your copy of the book.

Hints

Open one hint at a time. Try the exercise again after each.

Hint 1

Ask what makes a coroutine different from a subroutine. Count the places where control goes from one routine to the other.

Solution

Show the solution

A coroutine pair is useful only when each routine calls the other, and each call must be able to resume the other routine at a different place. Look at the cases in which this does not hold.

  • If routine A calls routine B from only one place, and B is never left in the middle, then B is a subroutine. The coroutine linkage adds work and gives nothing.
  • If B is called from several places in A, but always enters at the same point, it is again a subroutine. Often B can keep a switch or a state flag, and a normal entrance can choose the right place with a branch. Then also no real coroutine is needed.
  • A coroutine is worth its cost only when both routines have two or more places where they give up control, and each routine has its own state that is held in the program counter, not in data.

So a small example is too short to show the gain, and a large example is too long for a book. The data that pass between the routines must also be neither too simple (then a loop is enough) nor too complex (then the example needs pages of description). The example of the text, with a replication coroutine and a grouping coroutine, is about as small as one can make it while both routines still have more than one jump to the other.

Remarks

The same view explains why coroutines appear most in input and output, in simulation and in parsers. There the two sides have different structure, and neither is a natural caller of the other. See the C1 chapter on Section 1.4.2.

This solution is drafted, and a person has not reviewed it yet. The source.

In Lean

not stated yet The exercise is not stated in Lean yet.

The status is computed from the Lean build. The node of the map.

Something is wrong? Report it.