Flatten Scala Try

后端 未结 7 1032
天命终不由人
天命终不由人 2020-12-14 19:20

Is there a simple way to flatten a collection of try\'s to give either a success of the try values, or just the failure? For example:

def map(l:List[Int]) =          


        
7条回答
  •  鱼传尺愫
    2020-12-14 20:24

    As an addition to Impredicative's answer and comment, if you have both scalaz-seven and scalaz-contrib/scala210 in your dependencies:

    > scala210/console
    [warn] Credentials file /home/folone/.ivy2/.credentials does not exist
    [info] Starting scala interpreter...
    [info] 
    Welcome to Scala version 2.10.0 (OpenJDK 64-Bit Server VM, Java 1.7.0_17).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> import scala.util._
    import scala.util._
    
    scala> def map(l:List[Int]): List[Try[Int]] = l map {
         |   case 4 => Failure(new Exception("failed"))
         |   case i => Success(i)
         | }
    map: (l: List[Int])List[scala.util.Try[Int]]
    
    scala> import scalaz._, Scalaz._
    import scalaz._
    import Scalaz._
    
    scala> import scalaz.contrib.std.utilTry._
    import scalaz.contrib.std.utilTry._
    
    scala> val l1 = List(1,2,3,4,5,6)
    l1: List[Int] = List(1, 2, 3, 4, 5, 6)
    
    scala> map(l1).sequence
    res2: scala.util.Try[List[Int]] = Failure(java.lang.Exception: failed)
    
    scala> val l2 = List(1,2,3,5,6)
    l2: List[Int] = List(1, 2, 3, 5, 6)
    
    scala> map(l2).sequence
    res3: scala.util.Try[List[Int]] = Success(List(1, 2, 3, 5, 6))
    

    You need scalaz to get an Applicative instance for the List (hidden in the MonadPlus instance), to get the sequence method. You need scalaz-contrib for the Traverse instance of Try, which is required by the sequence's type signature. Try lives outside of scalaz, since it only appeared in scala 2.10, and scalaz aims to cross-compile to earlier versions).

提交回复
热议问题