使用Scalaz将Seq[A \/ B]
分区为(Seq[A], Seq[B])
的最佳方法是什么?
答案 0 :(得分:7)
MonadPlus中有一个方法:separate
defined。这个类型类是Monad和PlusEmpty(广义Monoid)的组合。因此,您需要为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已经是monadic,因此point
和bind
很容易,empty
和plus
是幺半群操作,Seq
是free monoid
2)Bifoldold [\ /]
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)
}
}
同样简单,标准折叠,但对于具有两个参数的类型构造函数。
现在您可以单独使用:
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))
<强>更新强>
感谢Kenji Yoshida,is有一个Bitraverse [\ /],所以你只需要MonadPlus。
使用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)
}
}