4 · Composing functions

An aggregate function is a plain JavaScript function: pass it around, compose it, reuse it.

Broadcast: spreading a value

The gradient tells you how far the source is. Share a value along with the distance, and every node also learns what its nearest source says. The shared value is an object {dist, value}. On the radio it travels as the array [dist, value], with no field names: every device runs the same program, so the receiver puts the names back from the initial value of share.

One colour per distinct value: each region "belongs" to a source. Add sources and watch the regions reorganise.

Blocks built on blocks

Once you have broadcast, a lot of things take one line. For example the distance between two special nodes, known to the whole network: node B computes its distance from A with a gradient, then broadcasts it.

Drag node 35 or the source: the whole network updates the value. Each function keeps its own messages, so two blocks never get mixed up, even when they use the same operators.

The standard library

The common blocks are ready-made in nbrjs/lib, available in every example on this site:

On a device you load it with require('nbrjs/lib').globals(); the playground does it for you when the program uses it.

Try it

1. Broadcast the source's round counter (rep): far nodes see older numbers. How much older, compared to the distance?

2. Count the nodes that can reach the source, and show the count everywhere.

Solutions
var program = () => {
  var clock = rep(0, (c) => c + 1);
  return clock - broadcast(sense('source'), clock);  // delay: about the hops from the source
};

var program = () => {
  var source = sense('source');
  return broadcast(source, collectSum(hopsTo(source), 1));
};