FlatMap behavior when applied to List [Option [T]]

Take a look at this code:

scala> val a = List(Some(4), None)
a: List[Option[Int]] = List(Some(4), None)
scala> a.flatMap( e=> e)
List[Int] = List(4)

Why does using flatMapa function { e => e }on List[Option[T]]return a List[T]with elements removed None?

In particular, what is the conceptual reasoning behind it - is it based on some existing theory in functional programming? Is this behavior common in other functional languages?

It, while really useful, feels a bit magical, but at the same time arbitrary.

EDIT:

Thank you for your feedback and response. I rewrote my question in order to pay more attention to the conceptual nature of the question. Instead of the specific implementation details of Scala, I'm more interested in knowing formal concepts.

+4
2

, flatMap:

scala> List(1, 2).flatMap {
     |   case i if i % 2 == 0 => Some(i)
     |   case i => None
     | }
res0: List[Int] = List(2)

, Option - Option[A] Iterable[A], GenTraversableOnce[A], , flatMap .

, ( , , ), Scala , .. Haskell for , mapMaybe .

+7

Compalion Scaladoc for Option. :

implicit def option2Iterable[A](xo: Option[A]): Iterable[A]

, Iterable, . Option[A], Iterable[A], .

:

val a = List(Some(4), None)
a.flatMap(e => e)

List.flatMap, A => GenTraversableOnce[B]. A Option[Int], B Int, e, , Option[Int] Iterable[Int] ( GenTraversableOnce).

:

List(List(1), Nil).flatMap(e => e)

, :

List(Option(1), None).flatMap(e => e.toList)

flatMap , Scala: A => List[B] ( , ) List[B], .

+4

All Articles