[英]Partition a sequence of disjunctions in Scalaz
使用Scalaz将Seq[A \\/ B]
划分为(Seq[A], Seq[B])
的最佳方法是什么?
There is a method: separate
defined in MonadPlus. 有一种方法,包括: separate
定义在MonadPlus。 This typeclass is a combination a Monad with PlusEmpty (generalized Monoid). 这个类型类是Monad和PlusEmpty(广义Monoid)的组合。 So you need to define instance for Seq
: 所以你需要为Seq
定义实例:
1) MonadPlus[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 Seq已经是monadic,所以point
和bind
很容易, empty
, plus
是monoid操作而Seq
是一个免费的monoid
2) Bifoldable[\\/] 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)
}
}
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. 由于吉田健二 ,有是一个Bitraverse [\\ /],所以你只需要MonadPlus。
And a simple solution using foldLeft
: 使用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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.