scala - 泛型函数类型中的通用量化

标签 scala types type-theory parametric-polymorphism

阅读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/

相关文章:

scala:如何将 ArrayBuffer 转换为 Set?

Scala私有(private)函数

mysql - 在 MySQL 上创建类型

dependent-type - 在依赖类型的编程语言中,Type-in​​-Type 是否适用于编程?

logic - Agda 中的排中律

使用 Scala 进行安卓开发

scala - X 类采用类型参数

actionscript-3 - 如何在 ActionScript 3 中创建一个接受多种参数类型的函数?

haskell - Liquid Haskell 的表达能力

type-inference - 编译器如何知道返回正确的类型?