質問

What is the best way to partition Seq[A \/ B] into (Seq[A], Seq[B]) using Scalaz?

役に立ちましたか?

解決

There is a method: separate defined in MonadPlus. This typeclass is a combination a Monad with PlusEmpty (generalized Monoid). So you need to define instance for Seq:

1) MonadPlus[Seq]

implicit val seqmp = new MonadPlus[Seq] {
  def plus[A](a: Seq[A], b: => Seq[A]): Seq[A] = a ++ b
  def empty[A]: Seq[A] = Seq.empty[A]
  def point[A](a: => A): Seq[A] = Seq(a)
  def bind[A, B](fa: Seq[A])(f: (A) => Seq[B]): Seq[B] = fa.flatMap(f)
}

Seq is already monadic, so point and bind are easy, empty and plus are monoid operations and Seq is a free monoid

2) Bifoldable[\/]

implicit val bife = new Bifoldable[\/] {
    def bifoldMap[A, B, M](fa: \/[A, B])(f: (A) => M)(g: (B) => M)(implicit F: Monoid[M]): M = fa match {
      case \/-(r) => g(r)
      case -\/(l) => f(l)
    }

    def bifoldRight[A, B, C](fa: \/[A, B], z: => C)(f: (A, => C) => C)(g: (B, => C) => C): C = fa match {
      case \/-(r) => g(r, z)
      case -\/(l) => f(l, z)
    }
  }

Also easy, standard folding, but for type constructors with two parameters.

Now you can use separate:

val seq: Seq[String \/ Int] = List(\/-(10), -\/("wrong"), \/-(22), \/-(1), -\/("exception"))
scala> seq.separate
res2: (Seq[String], Seq[Int]) = (List(wrong, number exception),List(10, 22, 1))

Update

Thanks to Kenji Yoshida, there is a Bitraverse[\/], so you need only MonadPlus.

And a simple solution using foldLeft:

seq.foldLeft((Seq.empty[String], Seq.empty[Int])){ case ((as, ai), either) =>
  either match {
    case \/-(r) => (as, ai :+ r)
    case -\/(l) => (as :+ l, ai)
  }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top