Where is `sequence` in Scalaz7
Asked Answered
P

1

18

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?

Peristome answered 4/9, 2012 at 17:14 Comment(0)
U
29

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))
Unsociable answered 4/9, 2012 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.