Where is `sequence` in Scalaz7

北慕城南 提交于 2019-12-04 16:01:26

问题


I am learning Scalaz and I have a project that already makes use of Scalaz7. Following this question I would like to use the function

sequence[T](l: List[Option[T]]): Option[List[T]]

(not that it is hard to write it myself). But the aforementioned question mentions Scalaz6.

Where to find the sequence function in Scalaz7?


回答1:


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


来源:https://stackoverflow.com/questions/12268351/where-is-sequence-in-scalaz7

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