Skip to content

Instantly share code, notes, and snippets.

@nashid
Forked from cb372/sequence.scala
Created March 4, 2019 23:50
Show Gist options
  • Save nashid/f317958693134d54a2b512464fc0f053 to your computer and use it in GitHub Desktop.
Save nashid/f317958693134d54a2b512464fc0f053 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment