Universal quantification in generic function type

白昼怎懂夜的黑 提交于 2019-12-21 21:18:11

问题


Reading the paper on Types and Polymorphism in programming languages, i wondered is it possible to express the similar universal quantification on type members with Scala. Example from the paper:

type GenericID = ∀A.A ↦ A

Which is a type for generic identity function and the following example in their paper language Fun was correct:

value inst = fun(f: ∀a.a ↦ a) (f[Int], f[Bool])
value intId = fst(inst(id))   // return a function Int ↦ Int

Is there some way to express the similar thing in Scala?

This is not the same as type constructor type GenericId[A] = A => A, cause it's a type operation when ∀A.A ↦ A is a type for generic function


回答1:


Following on from my comment above:

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})

In other words, identity of types has not been preserved by 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}")



回答2:


Try: 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)


来源:https://stackoverflow.com/questions/19398087/universal-quantification-in-generic-function-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!