它定义在scalaz.Traverse https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Traverse.scala类型类,它看起来像这样:
def sequence[G[_]:Applicative,A](fga: F[G[A]]): G[F[A]] =
traversal[G].run[G[A], A](fga)(ga => ga)
scalaz.syntax.TraverseOps https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/syntax/TraverseSyntax.scala提供了一个可以拉皮条的版本List
, since List
has a Traverse
实例。
您可以只导入您需要的内容:
import scalaz._, std.list._, std.option._, syntax.traverse._
或者所有东西和厨房水槽:
import scalaz._, Scalaz._
然后你可以像这样使用它:
scala> val xs: List[Option[Int]] = Some(1) :: Some(2) :: Nil
xs: List[Option[Int]] = List(Some(1), Some(2))
scala> xs.sequence
res0: Option[List[Int]] = Some(List(1, 2))
或者,如果您想要问题中的确切表述:
scala> def sequence[T](l: List[Option[T]]): Option[List[T]] = l.sequence
sequence: [T](l: List[Option[T]])Option[List[T]]
scala> sequence(xs)
res1: Option[List[Int]] = Some(List(1, 2))