scala 如何在类型中定义的范围内有意义地使用Scala中的函数类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7376789/
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
How to use the function type in scala within defined in type meaningfully?
提问by Clark Bao
I am new and naive to scala. Just know how to define a function type such as Set here(only as an example).
我是 Scala 的新手和天真。只知道如何定义一个函数类型,例如这里的 Set(仅作为示例)。
type Set = Int => Boolean
def set(i: Int): Set = n => n == i
def contains(s: Set, i: Int) = s(i)
I also read the wiki of language-agnostic function type. It seems C#,C,Haskel also have the similiar grammer. http://en.wikipedia.org/wiki/Function_type.
我还阅读了语言不可知函数类型的维基。似乎 C#、C、Haskel 也有类似的语法。 http://en.wikipedia.org/wiki/Function_type。
My question is in which case you prefer to define one of this kind of abstract type function and use it,
And no other choice to reach the same target? Comparing to directly define a concrete method using def
我的问题是在哪种情况下您更喜欢定义一种这种抽象类型的函数并使用它,而没有其他选择来达到相同的目标?比较直接定义一个具体的方法使用def
Or I can loose the requirement, to say using this function type, I can make the code looks much better. So that I can know more about function type.
或者我可以放宽要求,比如说使用这个函数类型,我可以让代码看起来更好。这样我就可以了解更多关于函数类型的信息。
Here my main interested part is type Set = Int => Boolean,when you want to abstract it out? I am looking for real life use case, and how to implement it in concrete method in scala grammer.
For example, this one is a bit complex.
这里我主要感兴趣的部分是type Set = Int => Boolean,你什么时候想把它抽象出来?我正在寻找现实生活中的用例,以及如何在 Scala 语法中以具体方法实现它。例如,这个有点复杂。
type Set2 = (Int,Int,String) => (Boolean => Int) => (Boolean => Int).
I know it's called higher-kinded types. The grammer itself is indeed meaningful. But I just need more plain real life examples to scala beginners.
我知道它被称为高级类型。语法本身确实是有意义的。 但我只需要更简单的现实生活示例来帮助 Scala 初学者。
I found this answer describing for it. What is a higher kinded type in Scala?
我发现这个答案描述了它。 Scala 中的高级类型是什么?
But it still looks a bit obscure for me. I prefer plain answer for beginner. It seems like the function itself didn't require anything except the parameter and result type to the implementation mentod.For example, if the result (Boolean) doesn't come from parameter (Int) ,it still compiles.
但对我来说它仍然看起来有点模糊。我更喜欢初学者的简单答案。 除了实现mentod的参数和结果类型之外,函数本身似乎不需要任何东西。例如,如果结果 (Boolean) 不是来自参数 (Int) ,它仍然会编译。
def set(i: Int): Set1 = aa => new Date().getDate() == i
Am I unstanding it right?
我不明白吗?
Let me know why this question is not clear or bad, so I can improve it,Sir!
让我知道为什么这个问题不清楚或不好,所以我可以改进它,先生!
回答by agilesteel
The keyword typein Scala creates an alias for a given type. For example:
typeScala 中的关键字为给定类型创建别名。例如:
scala> type Str = String
defined type alias Str
scala> val greeting: Str = "Hello World!"
greeting: Str = Hello World!
This is very similar to what you did:
这与您所做的非常相似:
scala> type Set = Int => Boolean
defined type alias Set
scala> val isEven: Set = _ % 2 == 0
isEven: Int => Boolean = <function1>
scala> println(isEven(4))
true
scala> println(isEven(5))
false
Although type aliases may sometimes be useful for clarification purposes, documentation is not their primary use case. Scala's type system is very sophisticated. For instance there is an alternative to generics, namely abstract types. Consider this:
尽管类型别名有时可能有助于澄清目的,但文档并不是它们的主要用例。Scala 的类型系统非常复杂。例如,有一种泛型的替代方案,即抽象类型。考虑一下:
// Generics
abstract class GenericAbstraction[TypeArgument]
class GenericConcrete extends GenericAbstraction[String]
// Abstract types
abstract class TypeAbstraction {
type TypeArgument
}
class TypeConcrete extends TypeAbstraction {
type TypeArgument = String
}
These code samples basically accomplish the same thing, but there are situations where you need abstract types, but can't (or shouldn't) use generics. You can find more information here.
这些代码示例基本上完成了相同的事情,但在某些情况下您需要抽象类型,但不能(或不应该)使用泛型。您可以在此处找到更多信息。
回答by Don Mackenzie
You can define a function literal as follows:
您可以按如下方式定义函数字面量:
val incrementor = (x: Int) => x + 1
or if you have some context that can be used by Scala's type inference, you can use reduced forms like:
或者如果你有一些可以被 Scala 的类型推断使用的上下文,你可以使用简化的形式,如:
val listOfInt = List(1, 2, 3, 4, 5)
listOfInt map {x => x + 1}
listOfInt map {_ + 1}
or even
甚至
listOfInt map {1 +}
These literals all imply the type themselves or have their type constrained by the expected type of a higher order function they are being passed to.
这些文字都暗示了类型本身,或者它们的类型受到它们被传递给的高阶函数的预期类型的约束。
There have been several questions on SO about the difference between functions and methods which would be good background reading but perhaps taking a look at the free version of Martin Odersky's book Programming in Scala (Version 1)would be a much better starting point to read up about functions and methods.
关于函数和方法之间的区别,有几个关于 SO 的问题,这将是很好的背景阅读,但也许看看 Martin Odersky 的书Programming in Scala (Version 1)的免费版本会是一个更好的起点来阅读关于函数和方法。
回答by Clark Bao
I am considering like this. The function definition in the type is abstract, which makes it possible to define different concrete methods to implement them. I think it is called Polymorphism or later binding. which makes it possible to bind the function type and concrete method later in the runtime.
我是这样考虑的。类型中的函数定义是抽象的,这使得可以定义不同的具体方法来实现它们。我认为它被称为多态性或后来的绑定。这使得稍后在运行时绑定函数类型和具体方法成为可能。
I think in JAVA, you cannot override an abstract method by static method. But in functional language, it seems very naturally to define concrete method to implement the abstract function. Please correct me if I am wrong.
我认为在 JAVA 中,您不能通过静态方法覆盖抽象方法。但是在函数式语言中,定义具体的方法来实现抽象的功能似乎很自然。如果我错了,请纠正我。
Look at this about "polymorphic-functions".
看看这个关于“多态函数”的内容。
http://gleichmann.wordpress.com/2011/01/23/functional-java-polymorphic-functions/
http://gleichmann.wordpress.com/2011/01/23/functional-java-polymorphic-functions/
But the conclusion is sad to me. We can only simulate it in scala. Check this from the link.
但是这个结论让我很伤心。我们只能在scala中模拟它。从链接中检查。
"Wow, what a journey. We saw that it's not possible to directly define polymorphic functions in Scala. Instead there are some work arounds to kind of simulating them. It all comes down to the fact, that a function is a value of a certain Function type, which needs to be type parameterized at runtime, that is all type parameters need to be type parameterized for getting a real value (or instance of that type)."
“哇,真是一段旅程。我们看到在 Scala 中无法直接定义多态函数。相反,有一些解决方法可以模拟它们。这一切都归结为这样一个事实,即函数是某个值函数类型,需要在运行时进行类型参数化,即所有类型参数都需要进行类型参数化以获取实际值(或该类型的实例)。”
"So as a last conclusion, defining polymorphic functions is possible, but the consequences might outweight the benefits. As always, you need to be aware of the given risks and decide for yourself if it's worth the trade offs (which i hope to have shown to you) for your concrete problem area …"
“所以作为最后一个结论,定义多态函数是可能的,但后果可能会超过好处。一如既往,你需要意识到给定的风险并自己决定是否值得权衡(我希望已经表明给您)针对您的具体问题领域……”

