正在阅读paper http://lucacardelli.name/Papers/OnUnderstanding.A4.pdf关于编程语言中的类型和多态性,我想知道是否可以用 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[+_] = _ => _
.
Addendum
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}")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)