scala 有恒等函数吗?
如果我有类似 List[Option[A]]
的东西,并且我想将其转换为 List[A]
,标准方法是使用 flatMap
:
scala> val l = List(Some("Hello"), None, Some("World"))
l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World))
scala> l.flatMap( o => o)
res0: List[java.lang.String] = List(Hello, World)
现在o => o 只是一个恒等函数。我本以为会有某种方法可以做到:
l.flatMap(Identity) //return a List[String]
但是,我无法让它工作,因为你无法生成对象
。我尝试了一些方法但没有成功;有人有这样的工作吗?
If I have something like a List[Option[A]]
and I want to convert this into a List[A]
, the standard way is to use flatMap
:
scala> val l = List(Some("Hello"), None, Some("World"))
l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World))
scala> l.flatMap( o => o)
res0: List[java.lang.String] = List(Hello, World)
Now o => o
is just an identity function. I would have thought there'd be some way to do:
l.flatMap(Identity) //return a List[String]
However, I can't get this to work as you can't generify an object
. I tried a few things to no avail; has anyone got something like this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Predef 中有一个身份函数。
我认为 for 表达式更好:
编辑:
我试图找出为什么需要类型参数(Option[String])。问题似乎是从 Option[T] 到 Iterable[T] 的类型转换。
如果将恒等函数定义为:
类型参数可以省略。
There's an identity function in Predef.
A for expresion is nicer, I suppose:
Edit:
I tried to figure out why the the type parameter (Option[String]) is needed. The problem seems to be the type conversion from Option[T] to Iterable[T].
If you define the identity function as:
the type parameter can be omitted.
FWIW,在 Scala 2.8 上,您只需调用
flatten
即可。 Thomas 大部分内容都涵盖了 Scala 2.7。他只错过了使用该标识的一种替代方法:但是,它不适用于运算符表示法(运算符表示法似乎不接受类型参数,这一点很高兴知道)。
您还可以在 Scala 2.7 上调用
flatten
(至少在List
上),但如果没有类型。然而,这有效:FWIW, on Scala 2.8 you just call
flatten
on it. Thomas has it mostly covered for Scala 2.7. He only missed one alternative way of using that identity:It won't work with operator notation, however (it seems operator notation does not accept type parameters, which is good to know).
You can also call
flatten
on Scala 2.7 (on aList
, at least), but it won't be able to do anything without a type. However, this works:您可以为类型推断器提供一些帮助:
You could just give the type inferencer a little help:
斯卡拉3:
Scala 3: