我在谈论这个(并且只谈论参数多态性):
def fun1[T](s: Set[T]): Option[T] = s.headOpton
我在一些地方看到,人们将其称为
T
周围的多态函数示例。在原始 scala 中 - 类似于无形中 Set ~> Option
.但我不明白为什么我们可以称之为多态。即使我们似乎都可以通过
Set[Int]
和 Set[String]
现实中fun1[Int]
和 fun1[String]
是两个不同的功能。我想我可以声称这是因为 fun1
的 eta 扩展是错误的,并没有给我们想要的:scala> fun1 _
res0: Set[Nothing] => Option[Nothing] = <function1>
并且我们在展开时需要总是提到一个类型:
scala> fun1[Int]_
res1: Set[Int] => Option[Int] = <function1>
我正在尝试研究无形,并尝试将它与原始 scala 进行比较 - 这就是问题的来源。我理解正确吗?
最佳答案
fun1
实现不依赖于类型 T
因此一般写成:
Using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without depending on their type.
(来源 Wikipedia)
我同意你提到的
fun1[Int]
和 fun1[String]
“是两个不同的功能”。这些都采用“具体类型”:Parametric polymorphism refers to when the type of a value contains one or more (unconstrained) type variables, so that the value may adopt any type that results from substituting those variables with concrete types.
(来源 Haskell wiki)
编辑 在@Travis 和@Miles 评论之后:
正如 Travis 清楚地解释的那样,我们可以在“普通 scala”中使用多态方法,但不能在多态函数中使用。在 this article Miles 使用
Poly
实现正是这个问题中提到的多态函数:object headOption extends PolyFunction1[Set, Option] {
def apply[T](l: Set[T]): Option[T] = l.headOption
}
scala> headOption(Set(1, 2, 3))
res2: Option[Int] = Some(1)
关于scala - 我们可以通过参数调用scala函数多态而不是无形吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34189382/