6/27
Part 2 of 7 · Count with messagesLearn and do

Each machine remembers who asked, and who has answered

A recursive call keeps its state on the stack: who called it, and the totals so far. A machine has no stack across messages. Between one receive and the next, everything it knows has to live on self.

What does a machine need to remember?

  • Its parent. The machine that asked it. It learns this from from_id of the first ask, and it sends its answer there.
  • The answers so far, in a dict from child id to that child's count. A dict, not a running total, because later you'll need to know which children have answered.

Here is the five-machine tree partway through the last step's fifo run, after message 6:

After 3 has answered and 4 hasn't
0parent None, replies {2: 1}
1parent 0, replies {3: 1}
3answered 1
4asked
2answered 1
waiting done

When an ask arrives, a machine stores the asker as its parent and sends an ask to each child. A machine with no children has nobody to wait for, so it answers 1 at once. That is the base case of the recursion.

The editor holds Machine, with its state set up in __init__: self.parent and self.replies. Write the ask branch of receive: store the parent, ask each child in list order, and answer at once when there are no children.