4.4

Write a function sequence that combines a list of Options into one Option containing a list of all the Some values in the original list. If the original list contains None even once, the result of the function should be None; otherwise the result should be Some with a list of all the values. Here is its signature

def sequence[A](a: List[Option[A]]): Option[List[A]]

Solution

object Main extends App {
  override def main(args: Array[String]): Unit = {
    println("sequence(List(Some(1), Some(2))): " + sequence(List(Some(1), Some(2))))
    println("sequence(List(Some(1), Some(2))): " + sequence(List(Some(1), None)))
  }

  def sequence[A](a: List[Option[A]]): Option[List[A]] = {
    val someValues: List[A] = a.filter(_ != None).map(_.get)
    if(someValues.size == a.size) Some(someValues)
    else None
  }
}

Output

sequence(List(Some(1), Some(2))): Some(List(1, 2))
sequence(List(Some(1), Some(2))): None