Last active
October 26, 2020 12:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
@fancywriter: you need to use type Lambda:
https://stackoverflow.com/questions/55979167/scalaz-7-how-to-use-functor-with-function1