summaryrefslogtreecommitdiff
path: root/core/src/mill/util/EitherOps.scala
blob: da2552c80662d724f59c03ff0b06848537e5a343 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mill.util

import scala.collection.generic.CanBuildFrom
import scala.collection.mutable
import scala.language.higherKinds

object EitherOps {

  // implementation similar to scala.concurrent.Future#sequence
  def sequence[A, B, M[X] <: TraversableOnce[X]](in: M[Either[A, B]])(
      implicit cbf: CanBuildFrom[M[Either[A, B]], B, M[B]]): Either[A, M[B]] = {
    in.foldLeft[Either[A, mutable.Builder[B, M[B]]]](Right(cbf(in))) {
        case (acc, el) =>
          for (a <- acc; e <- el) yield a += e
      }
      .map(_.result())
  }
}