David Portabella David Portabella - 2 months ago 15
Scala Question

What are the equivalent Option's sequence and traverse methods for \/?

on scalaz 7.2.6, this works:

// import scalaz.syntax.traverse._

List(1.some, 2.some, 3.some).sequence
res12: Option[List[Int]] = Some(List(1, 2, 3))

List(1.some, none, 3.some).sequence
res13: Option[List[Int]] = None

def doubleSmall(x: Int) = if (x < 30) (x * 2).some else none
List(1,2,3).traverse(doubleSmall)
res15: Option[List[Int]] = Some(List(2, 4, 6))


The following code does not compile. Is there an equivalent of
Option
's
sequence
and
traverse
methods for
\/
?

List(1.right, 2.right, 3.right).sequence
expecting something like: List(1, 2, 3).right

List(1.right, "error2".left, "error3".left).sequence
expecting something like: Seq("error2", "error3").left


val doubleSmall(x: Int) = if (x < 30) (x * 2).right else "error".left
List(1,2,3).traverse(doubleSmall)

m-z m-z
Answer

You're looking for sequenceU and traverseU:

scala> List[\/[String, Int]](1.right, 2.right, 3.right).sequenceU
res3: scalaz.\/[String,List[Int]] = \/-(List(1, 2, 3))

scala> List(1.right, 2.right, 3.right, "a".left).sequenceU
res4: scalaz.\/[String,List[Int]] = -\/(a)

Note that the first example needs a type hint so that it can pick up the proper implicit Unapply[Applicative, \/[String, Int]].

scala> List(1,2,3).traverseU(doubleSmall)
res9: scalaz.\/[String,List[Int]] = \/-(List(2, 4, 6))