Scala 泛型函数类型的通用量化

Scala 泛型函数类型的通用量化,scala,types,type-theory,parametric-polymorphism,Scala,Types,Type Theory,Parametric Polymorphism,在阅读有关编程语言中的类型和多态性的文章时,我想知道是否有可能用Scala来表示类型成员的类似通用量化。论文中的例子: type GenericID = ∀A.A ↦ A 这是通用标识函数的一种类型,以下纸质语言Fun中的示例是正确的: value inst = fun(f: ∀a.a ↦ a) (f[Int], f[Bool]) value intId = fst(inst(id)) // return a function Int ↦ Int 在Scala中是否有类似的表达方式 这与

在阅读有关编程语言中的类型和多态性的文章时,我想知道是否有可能用Scala来表示类型成员的类似通用量化。论文中的例子:

type GenericID = ∀A.A ↦ A
这是通用标识函数的一种类型,以下纸质语言Fun中的示例是正确的:

value inst = fun(f: ∀a.a ↦ a) (f[Int], f[Bool])
value intId = fst(inst(id))   // return a function Int ↦ Int
在Scala中是否有类似的表达方式


这与类型构造函数
type GenericId[A]=A=>A
不同,因为
∀A.A↦ A
是泛型函数的一种类型

scala> def f(x:List[Int]):Gen[List[Int]] = x.reverse
f: (x: List[Int])Gen[List[Int]]

scala> f(List(3,4))
res0: Function1[_, Any] = List(4, 3)

scala> def f(x:List[Number]):Gen[List[Number]] = x.reverse
f: (x: List[Number])Gen[List[Number]]

scala> f(List(3,4))
res1: Function1[_, Any] = List(4, 3)

以下是我的上述评论:

scala> type Gen[+_] = _ => _
defined type alias Gen

scala> def f(x: List[Int]): Gen[List[Int]] = x map (y => s"{$y!$y}")
f: (x: List[Int])Gen[List[Int]]

scala> f(List(1, 4, 9))
res0: Function1[_, Any] = List({1!1}, {4!4}, {9!9})
换句话说,
Gen[+\u]=\ u=>\ ucode>没有保留类型的标识

附录

scala> type Identity[A] = A => A
defined type alias Identity

scala> def f(x: List[Int]): Identity[List[Int]] = x => x.reverse
f: (x: List[Int])List[Int] => List[Int]

scala> f(List(1, 4, 9))
res1: List[Int] => List[Int] = <function1>

scala> def g(x: List[Int]): Identity[List[Int]] = x => x map (y => s"{$y!$y}")
<console>:35: error: type mismatch;
 found   : List[String]
 required: List[Int]
       def g(x: List[Int]): Identity[List[Int]] = x => x map (y => s"{$y!$y}")
scala>类型标识[A]=A=>A
定义的类型别名标识
scala>def(x:List[Int]):Identity[List[Int]=x=>x.reverse
f:(x:List[Int])List[Int]=>List[Int]
scala>f(列表(1,4,9))
res1:List[Int]=>List[Int]=
scala>def g(x:List[Int]):Identity[List[Int]=x=>x映射(y=>s“{$y!$y}”)
:35:错误:类型不匹配;
找到:列表[字符串]
必需:列表[Int]
def g(x:List[Int]):标识[List[Int]=x=>x映射(y=>s“{$y!$y}”)

试试看:
键入Gen[+\u]=\ u=>\ u
我认为您的示例并没有达到它看起来的效果。
Gen[+\u]=\ u=>\ u
中的每个
实例都是单独量化的。如果您使用实类型参数,比如
a
,您会发现除非删除协方差注释,否则它不会编译。