score:82
sequence
is used to gather together applicative effects. More concretely, it lets you "flip" F[G[A]]
to G[F[A]]
, provided G
is Applicative
and F
is Traversable
. So we can use it to "pull together" a bunch of Applicative
effects (note all Monad
s are Applicative
):
List(Future.successful(1), Future.successful(2)).sequence : Future[List[Int]]
// = Future.successful(List(1, 2))
List(4.set("abc"), 5.set("def")).sequence : Writer[String, List[Int]]
// = List(4, 5).set("abcdef")
traverse
is equivalent to map
then sequence
, so you can use it when you have a function that returns an Applicative
and you want to just get a single instance of your Applicative
rather than a list of them:
def fetchPost(postId: Int): Future[String]
//Fetch each post, but we only want an overall `Future`, not a `List[Future]`
List(1, 2).traverse[Future, String](fetchPost): Future[List[String]]
traverseU
is the same operation as traverse
, just with the types expressed differently so that the compiler can infer them more easily.
def logConversion(s: String): Writer[Vector[String], Int] =
s.toInt.set(Vector(s"Converted $s"))
List("4", "5").traverseU(logConversion): Writer[Vector[String], List[Int]]
// = List("4", "5").map(logConversion).sequence
// = List(4.set("Converted 4"), 5.set("Converted 5")).sequence
// = List(4, 5).set(Vector("Converted 4", "Converted 5"))
traverseM(f)
is equivalent to traverse(f).map(_.join)
, where join
is the scalaz name for flatten
. It's useful as a kind of "lifting flatMap":
def multiples(i: Int): Future[List[Int]] =
Future.successful(List(i, i * 2, i * 3))
List(1, 10).map(multiples): List[Future[List[Int]]] //hard to work with
List(1, 10).traverseM(multiples): Future[List[Int]]
// = List(1, 10).traverse(multiples).map(_.flatten)
// = List(1, 10).map(multiples).sequence.map(_.flatten)
// = List(Future.successful(List(1, 2, 3)), Future.successful(List(10, 20, 30)))
// .sequence.map(_.flatten)
// = Future.successful(List(List(1, 2, 3), List(10, 20, 30))).map(_.flatten)
// = Future.successful(List(1, 2, 3, 10, 20, 30))
Source: stackoverflow.com
Related Query
- How to understand traverse, traverseU and traverseM
- How to use Scalaz's traverse and traverseU with Either
- Understand how to use apply and unapply
- How to understand the two sentences about "Covariance" and "Contravariance"?
- How to traverse array from both left to right and from right to left?
- How to understand the "println" statements in both `for` and `yield`
- How to understand and use scala macro, and write a more complex function
- How to traverse Git repositories with JGit and draw a graph
- How to use the traverse TypeClass to accumulate state based on the elements and then map over the state and elements?
- How to configure a Play application to use Let's Encrypt certificate and to convert let's encrypt certificate so that play can understand it?
- How to traverse List[IO] to execute everything and collect all errors?
- How to understand the use of supertypes and variance in Scala's Option?
- Dimensions of a collection, and how to traverse it in an efficient, elegant manner
- how to understand the flip in autobundle() and in makeios?
- How to traverse a Set[Future[Option[User]]] and mutate a map
- how to traverse both success and fail results in ValidationNEL?
- How to best way to parse args yet make it clear and easy to understand
- What is a TypeTag and how do I use it?
- How to clone a case class instance and change just one field in Scala?
- Why doesn't the example compile, aka how does (co-, contra-, and in-) variance work?
- How to optimize for-comprehensions and loops in Scala?
- What are the relationships between Any, AnyVal, AnyRef, Object and how do they map when used in Java code?
- How can I use map and receive an index as well in Scala?
- How does type Dynamic work and how to use it?
- How to declare empty list and then add string in scala?
- What is "polymorphism a la carte" and how can I benefit from it?
- How to manage multiple interdependent modules with SBT and IntelliJ IDEA?
- How to use JDBC source to write and read data in (Py)Spark?
- How to write database-agnostic Play application and perform first-time database initialization?
- How can I get complete stacktraces for exceptions thrown in tests when using sbt and testng?
More Query from same tag
- map a function on a sequence of tuples
- Sliding Window without watermark in Apache Spark?
- Assert that class recovered through runtime reflection is a subclass of another class
- How to find intersection of dataframes based on multiple columns?
- Code coverage for scala with separate test project in java
- Shapeless HList return type
- Type mismatch when using higher-kinded types
- how to get parent folder name in spark?
- Get auto-generated ID from INSERT by Slick Plain SQL
- Convert a List[String] to a case class using Shapeless
- How a Spark executor runs multiple tasks?
- Transform Array[Seq[(Int, String)]] to Seq[(Int, String)] in SCALA
- How to import several implicit at once?
- How can i process the empty strings present in records and get if processed via Spark-Scala?
- Task serialization issue when using SparkML prediction model
- Anyone tried using Scalatra application in cloudfoundry
- How to apply User Defined Function on each subset formed by a Group By Operation in Apache Spark?
- Case classes memory consumption
- sbt package not adding dependencies
- Spark: read csv file from s3 using scala
- Are Scala constructor args duplicated?
- Spark atop of Docker not accepting jobs
- Play Framework: Gzip compression/decompression of data over WebSocket
- How to integrate Spark with Scala project in IntelliJ IDE?
- Difference between df.SaveAsTable and spark.sql(Create table..)
- Scala 2.13 migration
- How to store custom objects in Dataset?
- Large Docker context slowing down docker-compose build
- How to reuse Scala type class based API from typeless REST API
- Regex divide string by commas ignoring function syntax