Last active
July 22, 2024 22:53
-
-
Save frgomes/02b629c5956e9e41319b7f4a379e1063 to your computer and use it in GitHub Desktop.
FP - sequence :: Seq[Try[T]] to Try[Seq[T]]
This file contains hidden or 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
import scala.util.Try | |
implicit class SeqTryExtension[T](seq: Seq[Try[T]]) { | |
def sequence: Try[Seq[T]] = | |
seq | |
.foldRight(Try(List.empty[T])) { | |
case (item, acc) => for { a <- acc; i<- item } yield i :: a | |
} | |
} | |
implicit class MapStringTryExtension[T](map: Map[String, Try[T]]) { | |
import scala.collection.mutable.LinkedHashMap | |
implicit def sequence: Try[LinkedHashMap[String, T]] = | |
map | |
.foldRight(Try(LinkedHashMap.empty[String,T])) { | |
case (item, acc) => for { a <- acc; i<- item._2 } yield LinkedHashMap(item._1 -> i) ++ a | |
} | |
} |
Prints:
sf: scala.util.Try[Seq[Int]] = Failure((java.lang.RuntimeException: not a number)
ss: scala.util.Try[Seq[Int]] = Success(List(1, 2, 3, 4, 5))
mf: scala.util.Try[scala.collection.mutable.LinkedHashMap[String,String]] = Failure(java.lang.RuntimeException: failure)
ms: scala.util.Try[scala.collection.mutable.LinkedHashMap[String,String]] = Success(Map(a -> a, b -> b, c -> c, d -> d))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
import scala.util.{Try,Success,Failure}
// tests for Seq
val sf = Seq(Success(1), Success(2), Failure(new RuntimeException("not a number")), Success(4), Success(5))
val ss = Seq(Success(1), Success(2), Success(3), Success(4), Success(5))
println(tf.sequence)
println(tssequence)
// tests for Map
val mf = Map("a" -> Success("a"), "b" -> Success("b"), "c" -> Failure(new RuntimeException("failure")), "d" -> Success("d"))
val ms = Map("a" -> Success("a"), "b" -> Success("b"), "c" -> Success("c"), "d" -> Success("d"))
println(mf.sequence)
println(ms.sequence)