在Scalaz中划分一系列析取

时间:2013-10-21 03:10:53

标签: scala functional-programming scalaz

使用Scalaz将Seq[A \/ B]分区为(Seq[A], Seq[B])的最佳方法是什么?

1 个答案:

答案 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,因此pointbind很容易,emptyplus是幺半群操作,Seqfree 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 Yoshidais有一个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)
  }
}