List of options: equivalent of sequence in Scala?

后端 未结 7 637
别那么骄傲
别那么骄傲 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:50

    If you want a solution for just List and Option rather a general monad then following will do the job,

    def sequence[T](l : List[Option[T]]) = 
      if (l.contains(None)) None else Some(l.flatten)
    

    REPL session,

    scala> sequence(List(Some(1), None, Some(2)))
    res2: Option[List[Int]] = None
    
    scala> sequence(List(Some(1), Some(2), Some(3)))
    res3: Option[List[Int]] = Some(List(1, 2, 3)) 
    

    Update 20/8/2014

    Just use Scalaz ...

提交回复
热议问题