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

Broken forEach on CovariantIdentityBoth #1194

Closed
felher opened this issue Sep 16, 2023 · 0 comments · Fixed by #1193
Closed

Broken forEach on CovariantIdentityBoth #1194

felher opened this issue Sep 16, 2023 · 0 comments · Fixed by #1193
Assignees
Labels
bug Something isn't working

Comments

@felher
Copy link
Contributor

felher commented Sep 16, 2023

Hey all,

using forEach on a bunch of data types seems to give the wrong result:

println(List(List(1, 2), List(3)).forEach(identity))

gives List(List(1, 2, 3, 3), List(1, 2, 3, 3)), while it should give List(List(1, 3), List(2, 3)) or something like that.

The problem seems to be in trait CovariantIdentityBoth in "coherent.scala":

def forEach[A, B, Collection[+Element] <: Iterable[Element]](in: Collection[A])(f: A => F[B])(implicit
    bf: BuildFrom[Collection[A], B, Collection[B]]
  ): F[Collection[B]] =
    in.foldLeft(bf.newBuilder(in).succeed)((bs, a) => bs.zipWith(f(a))(_ += _)).map(_.result())

Here, a mutable builder is used to collect the results. _ += _ is passed to zipWith which then passes it to map. But functions given to map on Covariant can be called multiple times, as is the case for List. Also, both resulting sublists are built from the same shared builder, since += on a builder returns the same mutable builder, as opposed to say :+ on Vector, which returns a new one.

@adamgfraser adamgfraser self-assigned this Sep 16, 2023
@adamgfraser adamgfraser added the bug Something isn't working label Sep 16, 2023
@adamgfraser adamgfraser linked a pull request Sep 16, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants