划分Seq[A \/ B]
为(Seq[A], Seq[B])
使用 Scalaz 的最佳方法是什么?
问问题
957 次
1 回答
8
有一个方法:在 MonadPlus 中separate
定义。这个类型类是 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 已经是一元的,所以point
和bind
很容易,empty
并且plus
是幺半群运算并且Seq
是一个自由的幺半群
2) 可折叠[\/]
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,有一个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)
}
}
于 2013-10-21T04:23:22.483 回答