scala 有scala身份函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1797502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:45:50  来源:igfitidea点击:

Is there a scala identity function?

scalafunctional-programmingscala-option

提问by oxbow_lakes

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:

如果我有类似 a 的东西List[Option[A]]并且我想将其转换为 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)

Now o => ois just an identity function. I would have thought there'd be some way to do:

Nowo => o只是一个恒等函数。我原以为会有一些方法可以做到:

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?

但是,我无法使其正常工作,因为您无法将object. 我尝试了几件事无济于事;有没有人有这样的工作?

采纳答案by Thomas Jung

There's an identity function in Predef.

Predef 中有一个标识函数

l flatMap identity[Option[String]]

> List[String] = List(Hello, World)

A for expresion is nicer, I suppose:

A for 表达更好,我想:

for(x <- l; y <- x) yield y

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].

我试图弄清楚为什么需要类型参数 (Option[String])。问题似乎是从 Option[T] 到 Iterable[T] 的类型转换。

If you define the identity function as:

如果将恒等函数定义为:

l.flatMap( x => Option.option2Iterable(identity(x)))

the type parameter can be omitted.

类型参数可以省略。

回答by Daniel C. Sobral

FWIW, on Scala 2.8 you just call flattenon it. Thomashas it mostly covered for Scala 2.7. He only missed one alternative way of using that identity:

FWIW,在 Scala 2.8 上,您只需调用flatten它。Thomas主要针对 Scala 2.7 进行了介绍。他只错过了使用该身份的另一种方式:

l.flatMap[String](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 alsocall flattenon Scala 2.7 (on a List, at least), but it won't be able to do anything without a type. However, this works:

您还可以调用flattenScala 2.7(List至少在 a上),但如果没有类型,它将无法执行任何操作。但是,这有效:

l.flatten[String]

回答by David Winslow

You could just give the type inferencer a little help:

你可以给类型推断器一些帮助:

scala> val l = List(Some("Hello"), None, Some("World"))
l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World))

scala> l.flatten[String]
res0: List[String] = List(Hello, World)