为什么某些递归类型无法编译 [英] Why certain recursive types fail to compile

查看:48
本文介绍了为什么某些递归类型无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了我无法理解的类型检查错误.两段代码是一样的,但只有一段可以编译.编译器给出了完全无用的错误信息:

I run into typecheck error that I could not understand. Two pieces of code are alike, but only one compiles. The compiler gives totally useless error message:

错误:类型参数 [I] 不符合类型 DY 的类型参数边界 [I <: Sample.this.Y]

error: type arguments [I] do not conform to type DY's type parameter bounds [I <: Sample.this.Y]

有问题的代码:

trait Sample {
  type X
  type DX[I <: X] <: X
  type Y = Aux[X]
  type DY[I <: Y] <: Y
  type Z = Bux[X]
  type DZ[I <: Z] <: Z
  type DW[I <: Z#C] <: Z#C
}
type Aux[I] = Sample { type X = I }

trait Dep {
  type B
  type C = Aux[B]
}
type Bux[A] = Dep { type B = A }

type UseX[I <: S#X, S <: Sample] = S#DX[I] // ok
type UseY[I <: S#Y, S <: Sample] = S#DY[I] // fails
type UseZ[I <: S#Z, S <: Sample] = S#DZ[I] // ok
type UseW[I <: S#Z#C, S <: Sample] = S#DW[I] // fails

为什么我不能引用类型本身?

Why I could not reference the type itself?

我仍然像写问题时一样困惑.但我仍然设法欺骗编译器来完成他的工作.这只会加剧我的困惑.

I remain confused as much as was when I wrote the question. But I still managed to trick compiler into doing his work. And that only heightened my confusion.

问题是基于类型绑定接受或拒绝相同类型的参数.如果类型绑定与参数相同(因此引入递归),则它被拒绝.但是如果我将递归包装在一种类型中,它通常会被接受.所以我只需要中继递归调用

The problem is same type arguments are accepted or rejected based on type bound. If type bound is the same as argument (introducing recursion therefore) it is rejected. But if I wrap recursion in a type it is accepted normally. So all I need is to relay recursion call

trait Sample {
  type X
  type Y = Aux[X]
  type Z = Bux[X]
  type DY[I <: Y] <: Y
  type DD[I <: Z] = DY[I#C]
}

type UseY[I <: S#Y, S <: Sample] = S#DY[I] // still fails
type UseD[I <: S#Z, S <: Sample] = S#DD[I] // miraculously works

但是它需要在 Bux 包装器类型中包装每个类型级别的调用.

But it requires to wrap every type level call in the Bux wrapper type.

推荐答案

所以,S#Y 的意思是some type Y,定义在 S任何实例中".另一方面,type DY[I <: Y] 意味着I 必须是 this 中声明的 Y 的子类 实例".

So, S#Y means "some type Y, defined in any instance of S". On the other hand, type DY[I <: Y] means "I must be a subclass of Y declared in this instance".

所以,当你说 type UseY[I <: S#Y, S <: Sample] = S#DY[I] 时,它失败了,因为 I 被限制为来自 some SY 的子类,但是 DY 希望它是一个子类相同 S,其中声明了DY.

So, when you say type UseY[I <: S#Y, S <: Sample] = S#DY[I], it fails, because I is constrained to be a subclass of Y from some S, but DY wants it to be a subclass of the same S where DY is declared.

这篇关于为什么某些递归类型无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆