List of options: equivalent of sequence in Scala?

后端 未结 7 602
别那么骄傲
别那么骄傲 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 :: _))
    }
    
    0 讨论(0)
提交回复
热议问题