List of options: equivalent of sequence in Scala?

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

    Maybe this helps, as it traverses once only and use recursion

    def sequence[A](a: List[Option[A]]): Option[List[A]] =
    a match {
      case Nil => Some(Nil)
      case h :: rest => h.flatMap(x => sequence(rest).map(x :: _))
    }
    

提交回复
热议问题