List of options: equivalent of sequence in Scala?

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

    Here is the same function as above using a combination of foldRight and map/ flatmap that only has to traverse the list once:

      def sequence[A](lo: List[Option[A]]): Option[List[A]] = 
        lo.foldRight (Option(List[A]())) { (opt, ol) => 
          ol flatMap (l => opt map (o => o::l))
        }
    

    Or, if you prefer the for comprehension version:

      def sequence2[A](lo: List[Option[A]]): Option[List[A]] = 
        lo.foldRight (Option(List[A]())) { (opt, ol) =>
          for {l <- ol; o <- opt} yield (o::l)
        }
    

提交回复
热议问题