Lesson 11: Loops

Intermediate

Loops in a dataflow language work differently from textual for and while loops. In Phograph, a loop is a node whose body method is called repeatedly until a termination condition is met.

How loops work

A node marked with is_loop executes its body method over and over. Each iteration, the method’s outputs feed back as inputs to the next iteration. The initial inputs come from the wires connected to the loop node.

  constant 0 --> [loop: count-up] --> log
                     body: increment
                     terminates when value reaches 10

Termination modes

Each loop has a termination mode that controls when iteration stops:

Shift registers

A shift register carries state from one iteration to the next. You wire an initial value into the loop node, and each iteration the body reads the current value and produces a new one.

  Example: sum a list [1, 2, 3, 4, 5]

  constant [1,2,3,4,5] --> [loop: sum-list]
  shift register "acc" starts at 0
  body: acc + current-element --> acc (next iteration)
  terminates when list is exhausted
  output: 15

Example: count to 10

  constant 1 --> [loop: counter]
  shift register "i" starts at 1
  body:
    i --> log
    i --> + 1 --> i (next)
    i --> >= 10 --> if true, succeed
  termination: FinishOnSuccess
  output: 10

Each iteration, the body logs the current count, increments it, and checks whether the target has been reached. When i reaches 10 the body succeeds and the loop finishes.

What you learned