Where is `sequence` in Scalaz7

余生颓废 提交于 2019-12-03 10:01:46

It's defined in the scalaz.Traverse type class, where it looks like this:

def sequence[G[_]:Applicative,A](fga: F[G[A]]): G[F[A]] =
  traversal[G].run[G[A], A](fga)(ga => ga)

scalaz.syntax.TraverseOps provides a version that gets pimped onto List, since List has a Traverse instance.

You can either import just what you need:

import scalaz._, std.list._, std.option._, syntax.traverse._

Or everything and the kitchen sink:

import scalaz._, Scalaz._

And then you can use it like this:

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

Or if you want exactly the formulation in your question:

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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!