5 · Alignment and branches

Devices only exchange values computed by the same piece of the program. Around an if, this needs branch.

Alignment

Every aggregate operator gets a name from its position in the program: the first is x0, the second x1, and so on. Two devices exchange values only under the same name: they are aligned. This is what lets you compose blocks without them interfering.

What goes wrong with a plain if

On this line nodes 3 and 4 are obstacles (in black, shift+click to change them). Obstacles should share 100 among themselves, the others 1, and each shows the largest value it sees:

Nodes 2 and 5 show 100: wrong. Both nbr calls are the first operator of the program, so both are called x0: to the devices they are the same thing, and values leak across the border. The playground spots this and warns you under the editor.

branch

branch(condition, () => ..., () => ...) runs one side and puts the condition in the name:

Now nodes 2 and 5 show 1. The operators become b0.1/x0 and b0.0/x0: devices that took different sides are no longer aligned, and the network splits into two separate domains. Hover a node to see the names in its message.

When a plain if is fine

Only aggregate code needs branch. A condition on local values, like src ? 0 : d.min() + 1 inside share, is plain JavaScript. So is an early return with no aggregate code on its side, because nothing comes after it to shift:

var program = () => {
  if (sense('obstacle')) return null;
  return distanceTo(sense('source'));
};

Watch out for an operator inside an if followed by more operators: on the devices that skip it, all the following names shift by one.

The playground and scripts/bundle.js check your program and warn about aggregate code under if, ?:, &&, ||, loops and .map(). They never change it: the code that runs on the device is the code you wrote, whichever tool uploads it.

A gradient that goes around obstacles

With a branch, obstacles leave the computation, and the gradient flows around them.

To pick a function at run time, as in var f = c ? hopsTo : distanceTo; f(src), wrap your own functions with aggregate('name', fn): different functions then never share messages, at no cost in message size. The library functions already are, and the playground warns when one of yours is missing it.

Try it

1. Two separate worlds: nodes with x < 3 compute the gradient, the others count their neighbours.

2. Remove the branch from the obstacle gradient and use an early return instead. Why does it still work?

Solutions
var program = () => branch(sense('x') < 3, () => distanceTo(sense('source')), () => neighbourCount());

var program = () => {
  if (sense('obstacle')) return null;
  return distanceTo(sense('source'));
};

Obstacles run no aggregate code at all, so they send nothing under distanceTo's name and drop out of its domain, as with the branch.