LoginSignup
0
0

More than 5 years have passed since last update.

List[Option[A]] の Option を剥がす

Posted at

題名の通り。Option のリストから None を除外したい。
以下、3パターン (worse, better, best) 等価だが、当然 worse より best の方が良い。

val raw: List[Option[A]] = List(Some(a), None, Some(b), Some(c), None)

val worse: List[A] = {
    def splitOption(list: List[Option[A]]): List[A] = {
        list match {
            case Nil => Nil
            case Some(head) :: tail => head :: splitOption(tail)
            case None :: tail => splitOption(tail)
        }
    }
    splitOption(raw)
}

val better: List[A] = raw.flatMap(a => a)
val best: List[A] = raw.flatten
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0