David Portabella - 1 year ago 65

Scala Question

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`

`sequence`

`traverse`

`\/`

`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)

Answer Source

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))
```