Skip to content

Instantly share code, notes, and snippets.

@cb372
Last active October 26, 2020 12:52
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cb372/458df4a98a2abb29b03f0d6f42298835 to your computer and use it in GitHub Desktop.
Save cb372/458df4a98a2abb29b03f0d6f42298835 to your computer and use it in GitHub Desktop.
Using Cats Traverse to turn a List of Try into a Try of List
Welcome to the Ammonite Repl 0.8.0
(Scala 2.11.8 Java 1.8.0_91)
@ import scala.util.Try
import scala.util.Try
@ val listOfTries: List[Try[String]] = List(Try("a"), Try("b"), Try("c"))
listOfTries: List[Try[String]] = List(Success("a"), Success("b"), Success("c"))
// I have a List[Try[String]] but I actually want a Try[List[String]].
// I want it to be a Failure if any of the individual Trys was a Failure.
// Traverse to the rescue!
@ import $ivy.`org.typelevel::cats-core:0.8.1`
import $ivy.$
@ import cats.Traverse
import cats.Traverse
// This brings in an instance of Applicative for Try
@ import cats.instances.try_._
import cats.instances.try_._
// This brings in an instance of Traverse for List
@ import cats.instances.list._
import cats.instances.list._
@ val tryOfList = Traverse[List].sequence(listOfTries)
tryOfList: Try[List[String]] = Success(List("a", "b", "c"))
// Job done! Or, with a bit of syntax sugar...
@ import cats.syntax.traverse._
import cats.syntax.traverse._
@ val tryOfList2 = listOfTries.sequence
tryOfList2: Try[List[String]] = Success(List("a", "b", "c"))
// As pointed out by @philwills, the `traverse` method is also useful:
@ val listOfStrings = List("1", "2", "3")
listOfStrings: List[String] = List("1", "2", "3")
@ val tryOfList3 = listOfStrings.traverse(x => Try(x.toInt))
tryOfList3: Try[List[Int]] = Success(List(1, 2, 3))
@philwills
Copy link

Every time I've found a use for 'sequence' , I've found that it was preceded by a 'map' and the two could be combined into a 'traverse'.

@cb372
Copy link
Author

cb372 commented Dec 3, 2016

Good point @philwills. Added an example.

@fancywriter
Copy link

Can you give me a hint how to do the same thing with Either? Doesn't compile for me for some reason...

@Maatary
Copy link

Maatary commented Jul 5, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment