阅读paper关于编程语言中的类型和多态性,我想知道是否可以用 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> 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[+_] = _ => _
并未保留类型的同一性。 .
附录
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 - 泛型函数类型中的通用量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19398087/