Scalaz7中的“序列"在哪里 [英] Where is `sequence` in Scalaz7
问题描述
我正在学习 Scalaz,并且我有一个已经使用 Scalaz7 的项目.按照这个问题我想使用该功能
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]]
(并不是说自己写起来很难).但上述问题提到了Scalaz6.
(not that it is hard to write it myself). But the aforementioned question mentions Scalaz6.
Scalaz7 中的序列函数在哪里?
Where to find the sequence function in Scalaz7?
推荐答案
它定义在 scalaz.Traverse
类型类,如下所示:
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
提供了一个被拉到 List
的版本,因为 List
有一个 Traverse
实例.
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))
这篇关于Scalaz7中的“序列"在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!