Domanda

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?

È stato utile?

Soluzione

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))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top