\/的等效Option的sequence和traverse方法是什么?
What are the equivalent Option's sequence and traverse methods for \/?
在 scalaz 7.2.6 上,这有效:
// 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))
以下代码无法编译。 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)
您正在寻找 sequenceU
和 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)
请注意,第一个示例需要类型提示,以便它可以获取正确的隐式 Unapply[Applicative, \/[String, Int]]
。
scala> List(1,2,3).traverseU(doubleSmall)
res9: scalaz.\/[String,List[Int]] = \/-(List(2, 4, 6))
在 scalaz 7.2.6 上,这有效:
// 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))
以下代码无法编译。 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)
您正在寻找 sequenceU
和 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)
请注意,第一个示例需要类型提示,以便它可以获取正确的隐式 Unapply[Applicative, \/[String, Int]]
。
scala> List(1,2,3).traverseU(doubleSmall)
res9: scalaz.\/[String,List[Int]] = \/-(List(2, 4, 6))