有没有办法扩展Scala中存在类型量词的范围,以说服类型检查器两个变量具有相同的类型?

时间:2015-01-18 17:02:19

标签: scala types existential-type quantifiers

请考虑以下代码段:

case class Foo[A](a:A)
case class Bar[A](a:A)

def f[B](foo:Foo[Seq[B]], bar:Bar[Seq[B]]) = foo.a ++ bar.a

val s : Seq[T] forSome {type T} = Seq(1, 2, 3)

f(Foo(s), Bar(s))

最后一行无法输入check,因为Foo(s)的类型为Foo[Seq[T]] forSome {type T}Bar(s)的类型为Bar[Seq[T]] forSome {type T},即每个都有自己的存在量词。

这有什么办法吗?实际上我在编译时所知道的s就是它有这样一种存在类型。如何强制Foo(s)Bar(s)属于单个存在量词的范围?

这有意义吗?我对Scala和一般的花式类型都很陌生。

2 个答案:

答案 0 :(得分:1)

要清楚,

val s : Seq[T] forSome {type T} = Seq(1, 2, 3)

相当于

val s: Seq[_] = Seq(1, 2, 3)

我认为这个问题的答案是否定的。您需要使用范围内的类型参数/类型成员或具体类型。

您可以采用标记类型的一种方式:http://etorreborre.blogspot.com/2011/11/practical-uses-for-unboxed-tagged-types.html

type Tagged[U] = { type Tag = U }
type @@[T, U] = T with Tagged[U]
def tag[A, B](a: A): @@[A, B] = a.asInstanceOf[@@[A, B]]
trait ThisExistsAtCompileTime

case class Foo[A](a:A)
case class Bar[A](a:A)

def f[B](foo:Foo[Seq[B]], bar:Bar[Seq[B]]) = foo.a ++ bar.a

val s : Seq[@@[T, ThisExistsAtCompileTime] forSome {type T}] = Seq(1, 2, 3) map { x => tag[Any, ThisExistsAtCompileTime](x) }

f(Foo(s), Bar(s))

答案 1 :(得分:1)

我意识到可以通过一些重构来完成这项工作:

case class Foo[A](a:A)
case class Bar[A](a:A)

def f[B](foo:Foo[Seq[B]], bar:Bar[Seq[B]]) = foo.a ++ bar.a
def g[B](s1:Seq[B], s2:Seq[B]) = f(Foo(s1), Bar(s2))

val s : Seq[T] forSome {type T} = Seq(1, 2, 3)

g(s)

基本上我将调用包装在另一个函数fg,以保证两个序列具有相同的类型。