2

阅读关于编程语言中的类型和多态性的论文,我想知道是否有可能用 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

4

2 回答 2

2

继我上面的评论之后:

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}")
于 2013-10-16T20:57:56.957 回答
0

尝试:type Gen[+_] = _ => _

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)
于 2013-10-16T10:05:20.357 回答