flatMap应用于List时的行为[Option [T]] [英] Behavior of flatMap when applied to List[Option[T]]
问题描述
scala> val a = List(一些(4),无)
a:List [Option [Int]] = List(一些(4),无)
scala> a.flatMap(e => e)
List [Int] = List(4)
为什么要将 flatMap
与函数 {e =>在$
List [Option [T]]
上返回一个 List [T]
与 None
元素被删除?
具体来说,它背后的概念推理是什么 - 它是基于现有的函数式编程理论吗?这种行为在其他功能语言中是否很常见?
这虽然很有用,但它同时感觉有点神奇但随意。
编辑:
感谢您的反馈和答复。
我改写了我的问题,以便更加强调问题的概念性。
flatMap
: 阶>列表(1,2).flatMap {
|例如,如果我%2 == 0 =>有些(i)
|情况i =>无
| }
res0:List [Int] = List(2)
c $ c> Option 的随播对象包含从选项[A]
到 Iterable [A]
的隐式转换,它是 GenTraversableOnce [A]
,这就是 flatMap
作为参数函数的返回类型。
这是一个方便的习惯用语,但它并不存在于其他函数式语言(至少我熟悉的语言)中,因为它依赖于Scala混合的子类型,隐式转换等。Haskell for示例通过 mapMaybe
提供了类似的功能。 code>列表,但。
Let's 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 would applying flatMap
with the function { e => e }
on a List[Option[T]]
returns a List[T]
with the None
elements removed?
Specifically, what are the conceptual reasoning behind it -- is it based on some existing theory in functional programming? Is this behavior common in other functional languages?
This, while indeed useful, does feel a bit magical yet arbitrary at the same time.
EDIT:
Thank you for your feedbacks and answer. I have rewritten my question to put more emphasis on the conceptual nature of the question. Rather than the Scala specific implementation details, I'm more interested in knowing the formal concepts behind it.
I assume you mean the support for mapping and filtering at the same time with flatMap
:
scala> List(1, 2).flatMap {
| case i if i % 2 == 0 => Some(i)
| case i => None
| }
res0: List[Int] = List(2)
This works because Option
's companion object includes an implicit conversion from Option[A]
to Iterable[A]
, which is a GenTraversableOnce[A]
, which is what flatMap
expects as the return type for its argument function.
It's a convenient idiom, but it doesn't really exist in other functional languages (at least the ones I'm familiar with), since it relies on Scala's weird mix of subtyping, implicit conversions, etc. Haskell for example provides similar functionality through mapMaybe
for lists, though.
这篇关于flatMap应用于List时的行为[Option [T]]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!