Skip to content
This repository has been archived by the owner on Oct 8, 2024. It is now read-only.

flatMap should act like it does a yield * on each iterable #114

Closed
jorendorff opened this issue Jul 16, 2020 · 3 comments · Fixed by #194
Closed

flatMap should act like it does a yield * on each iterable #114

jorendorff opened this issue Jul 16, 2020 · 3 comments · Fixed by #194

Comments

@jorendorff
Copy link
Collaborator

jorendorff commented Jul 16, 2020

Currently Iterator.prototype.flatMap is specified roughly like this:

*flatMap(mapper) {
  for (let value of {[@@Iterator]: () => this}) {
    for (let innerValue of mapper(value)) {
      yield innerValue;
    }
  }
}

Arguably it should be more like this:

*flatMap(mapper) {
  for (let value of {[@@Iterator]: () => this}) {
    yield* mapper(value);
  }
}

This changes two details of behavior:

  • It causes the flatMap iterator helper's .throw(exc) method to forward the exception along to the inner iterator (consistent with other iterator helpers). Currently the inner iterator is instead closed, and exc is then thrown again.
  • It causes the flatMap iterator helper's .next(value) method to forward the value along to the inner iterator. Currently the inner iterator's .next() method is always called with no arguments.
@Jack-Works
Copy link
Member

Jack-Works commented Jul 17, 2020

*flatMap(mapper) {
  for (let value of {[@@Iterator]: () => this}) {
    yield* mapper(value);
  }
}

Let's assume this is an Iterable<T> while T is Iterable<Q>.

The current behavior is to call the mapper with the value Q but your suggested version is calling mapper with T which I think is not correct.

The correct semantics should be

*flatMap(mapper) {
  for (let value of {[@@Iterator]: () => this}) {
    yield* Iterator.from(value).map(mapper);
  }
}

@conartist6
Copy link

conartist6 commented Dec 22, 2020

@Jack-Works I think the current version is indeed calling mapper<T> not mapper<Q>. That would be in line with what Array.prototype.flatMap does at least.

@bakkot
Copy link
Collaborator

bakkot commented Jul 7, 2022

In #194 we went the other direction: now no iterator helpers act like they do yield *, because that's a generator thing rather than an iterator thing.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants