Universal quantification in generic function type

瘦欲@ 提交于 2019-12-04 16:08:04

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

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