Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding sequenceM method to Traverse #1394

Merged
merged 3 commits into from Oct 24, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 20 additions & 2 deletions core/src/main/scala/cats/Traverse.scala
Expand Up @@ -58,11 +58,11 @@ import simulacrum.typeclass
* scala> import cats.implicits._
* scala> def parseInt(s: String): Option[Int] = Either.catchOnly[NumberFormatException](s.toInt).toOption
* scala> val x = Option(List("1", "two", "3"))
* scala> x.traverseM(_.map(parseInt))
* scala> x.flatTraverse(_.map(parseInt))
* res0: List[Option[Int]] = List(Some(1), None, Some(3))
* }}}
*/
def traverseM[G[_], A, B](fa: F[A])(f: A => G[F[B]])(implicit G: Applicative[G], F: FlatMap[F]): G[F[B]] =
def flatTraverse[G[_], A, B](fa: F[A])(f: A => G[F[B]])(implicit G: Applicative[G], F: FlatMap[F]): G[F[B]] =
G.map(traverse(fa)(f))(F.flatten)

/**
Expand All @@ -83,6 +83,24 @@ import simulacrum.typeclass
def sequence[G[_]: Applicative, A](fga: F[G[A]]): G[F[A]] =
traverse(fga)(ga => ga)

/**
* Thread all the G effects through the F structure and flatten to invert the
* structure from F[G[F[A]]] to G[F[A]].
*
* Example:
* {{{
* scala> import cats.implicits._
* scala> val x: List[Option[List[Int]]] = List(Some(List(1, 2)), Some(List(3)))
* scala> val y: List[Option[List[Int]]] = List(None, Some(List(3)))
* scala> x.flatSequence
* res0: Option[List[Int]] = Some(List(1, 2, 3))
* scala> y.flatSequence
* res1: Option[List[Int]] = None
* }}}
*/
def flatSequence[G[_], A](fgfa: F[G[F[A]]])(implicit G: Applicative[G], F: FlatMap[F]): G[F[A]] =
G.map(sequence(fgfa))(F.flatten)

/**
* Behaves just like sequence, but uses [[Unapply]] to find the
* Applicative instance for G.
Expand Down
2 changes: 1 addition & 1 deletion tests/src/test/scala/cats/tests/SyntaxTests.scala
Expand Up @@ -122,7 +122,7 @@ object SyntaxTests extends AllInstances with AllSyntax {
val gfb: G[F[B]] = fa.traverse(f1)

val f2 = mock[A => G[F[B]]]
val gfb2: G[F[B]] = fa.traverseM(f2)
val gfb2: G[F[B]] = fa.flatTraverse(f2)

val fga = mock[F[G[A]]]
val gunit: G[F[A]] = fga.sequence
Expand Down