List of options: equivalent of sequence in Scala?

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

    First off, I recommend that you check out the API docs for List.

    As for a solution, this may not be the most graceful way to do it, but it'll work (and with no external dependencies):

    // a function that checks if an option is a None
    def isNone(opt:Option[_]) = opt match {
      case None => true
      case _ => false
    }
    
    //templated for type T so you can use whatever Options
    def optionifyList[T](list:List[Option[T]]) = list.exists(isNone) match {
      case true => None
      case false => Some(list.flatten)
    }
    

    And a test just to be sure...

    scala> val hasNone = Some(1) :: None :: Some(2) :: Nil
    hasNone: List[Option[Int]] = List(Some(1), None, Some(2))
    
    scala> val hasSome = Some(1) :: Some(2) :: Some(3) :: Nil
    hasSome: List[Some[Int]] = List(Some(1), Some(2), Some(3))
    
    scala> optionifyList(hasSome)
    res2: Option[List[Int]] = Some(List(1, 2, 3))
    
    scala> optionifyList(hasNone)
    res3: Option[List[Int]] = None
    

提交回复
热议问题