Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: chunked(size) method. #34

Open
arnolddevos opened this issue Aug 5, 2021 · 0 comments · May be fixed by #78
Open

Proposal: chunked(size) method. #34

arnolddevos opened this issue Aug 5, 2021 · 0 comments · May be fixed by #78

Comments

@arnolddevos
Copy link

arnolddevos commented Aug 5, 2021

The idea is to materialise a generator in chunks. Here is a sketch of the proposed operation as a non-member method:

def chunked[R](input: Generator[R], size: Int): Generator[Iterable[R]] =
  new Generator[Iterable[R]]:
    def generate(f: Iterable[R] => Generator.Action): Generator.Action =
      val builder = Iterable.newBuilder[R]
      var n = 0
      var action: Generator.Action = Generator.Continue
      input.generate {
        r =>
          if n < size then 
            if n == 0 then builder.sizeHint(size)
            builder.addOne(r) 
            n += 1
            action
          else
            action = f(builder.result) 
            builder.clear
            n = 0
            action
      }
      if n > 0 && action == Generator.Continue then f(builder.result)
      else action

In comparison, toBuffer, toList etc materialise the whole of the stream. The standard collection operations Iterator.grouped and Iterable.grouped are similar. Chunking is a fairly common streaming operation so I think the need for this would arise often enough. The choice of type Iterable for the chunks might or might not be the best.

@odisseus odisseus linked a pull request May 8, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant