List of options: equivalent of sequence in Scala?

后端 未结 7 600
别那么骄傲
别那么骄傲 2021-01-04 04:55

What is the equivalent of Haskell\'s sequence in Scala? I want to turn list of options into an option of list. It should come out as None if any of the options

7条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 05:36

    Scalaz defines sequence.

    Here's an example:

    scala> import scalaz._
    import scalaz._
    
    scala> import Scalaz._
    import Scalaz._
    
    scala> List(Some(1), None, Some(2)).sequence
    res0: Option[List[Int]] = None
    
    scala> List(some(1), some(2), some(3)).sequence
    res1: Option[List[Int]] = Some(List(1, 2, 3))
    

    Note that in the second example, you have to use Scalaz's some function to create a Some -- otherwise, the List is constructed as List[Some[Int]], which results in this error:

    scala> List(Some(1), Some(2), Some(3)).sequence
    :14: error: could not find implicit value for parameter n: scalaz.Applicative[N]
           List(Some(1), Some(2), Some(3)).sequence
    

    The Scalaz some(a) and none functions create Some and None values of type Option[A].

提交回复
热议问题