displaying Generators

For a cell evaluating to a typical value, as an expression cell, its value gets displayed implicitly:

html`count = 12`

If I want to assign it to a variable, then it will be a program cell, and I need to use display to display it explicitly:

const c = display(html`count = 12`);

For a cell evaluating to a Generator, as an expression cell, it gets consumed and it’s value gets displayed implicitly:

(async function*() {
  let c = 0;
  while (true) {
    yield html`c = ${c++}`;
    await Promises.delay(1000);
  }
})()

If I want to assign it to a variable, then it will be a program cell, and… well, I don’t think I can display it in place without additional “machinery”:

const counter = (async function*() {
  let c = 0;
  while (true) {
    yield html`c = ${c++}`;
    await Promises.delay(1000);
  }
})()

If I wrap the whole thing in display:

const counter = display((async function*() {
  let c = 0;
  while (true) {
    yield html`c = ${c++}`;
    await Promises.delay(1000);
  }
})())

then I get async Generator {} as the displayed value.

If I push display inside the yield:

const counter = (async function*() {
  let c = 0;
  while (true) {
    yield display(html`c = ${c++}`);
    await Promises.delay(1000);
  }
})()

then I get:

c = 0c = 1c = 2c = 3c = 4c = 5c = 6c = 7

as the displayed value, with each yield adding a new value instead of replacing the old one.

It is true that I can add an additional cell:

counter

and it will implicitly display the value of my generator. But that isn’t as clean and elegant as displaying the value in place.

Is this asymmetry between assigned and unassigned Generators (versus assigned and unassigned values) just baked into Observable 2.0?

It’s not so much whether the generator is assigned; it’s whether you’re looking at the value within the cell versus across cells (and of course you can only look at a value across cells if the value has been assigned a name).

The same principle applies to promises, which if displayed within a cell will show as Promise {}, but across cells you will see the implicitly awaited resolved value.

One of the design decisions for the upcoming automatic inspection of top-level variables work is whether counter above should show the yielded value (the value across cell boundaries) or the generator (the value within the declaring cell). I’d guess we want to show the former, which would be more consistent with what we show in the expression cell case, and hence you’d be able to name things without losing implicit inspection.