List of options: equivalent of sequence in Scala?

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

    Since you need to flatten anyway, just do it first...

    def sequence(lo: List[Option[A]]): Option[List[A]] = lo.flatten match {
        la: List[A] if(la.length == lo.length) => Some(la)
        _ => None
    }
    

    tail recursion might be quickest

提交回复
热议问题