我们可以通过参数调用scala函数多态而不是无形的

我在谈论这个(并且只涉及参数多态):

def fun1[T](s: Set[T]): Option[T] = s.headOpton

我在一些地方看到过,人们称之为原始标量中T周围的多态函数的例子 – 类似于无形Set~>选项.

但我不明白为什么我们可以称之为多态.即使我们似乎能够在那里传递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之后编辑评论:

正如特拉维斯清楚解释的那样,我们可以在“普通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)
点赞