加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

泛型 – 使用类型级计算时类型推断/类型检查失败

发布时间:2020-12-16 18:48:10 所属栏目:安全 来源:网络整理
导读:我在使用文件 Units.scala中定义的 metascala中的度量单位功能时遇到了问题. 对于本问题的其余部分,我将使用简化方案,只有一种单位类型,长度. 所以现实中的类型看起来像 Quantity[_1,_0,_0] ^ ^ ^ ^ ^ ^ ^ | | | | | | | | Mass | Crncy.| Mol | Length Time
我在使用文件 Units.scala中定义的 metascala中的度量单位功能时遇到了问题.

对于本问题的其余部分,我将使用简化方案,只有一种单位类型,长度.

所以现实中的类型看起来像

Quantity[_1,_0,_0] 
          ^   ^   ^   ^   ^   ^   ^
          |   |   |   |   |   |   |
          | Mass  | Crncy.|  Mol  |
       Length   Time    Temp. Lum.Intensity

这足以证明问题:

Quantity[_1]
          ^
          |
       Length

一旦需要推断类型,麻烦就开始了.

考虑这个例子(也看一下UnitsTest.scala的代码):

val length: Quantity[_1] = m(5)
val area:   Quantity[_2] = length * length // (1) Works
val dist:   Quantity[_1] = area / length   // (2) Doesn't work!

我在最后一行收到错误说:

type mismatch;
  found :
    scalax.units.Units.Quantity[
      scalax.units.Subtractables.-[
        scalax.units.Integers._2,scalax.units.Integers._1
      ]
    ]

  required:
    scalax.units.Units.Quantity[
      scalax.units.Integers._1
    ]

看起来编译器无法弄清楚当“减去维度”时,手头的类型等于数量[_1],例如. G.在(1)中从一个区域到另一个区域:

Quantity[_2 - _1] <<not equal to>> Quantity[_1]

令人困惑的是,它在“添加维度”时有效. G.像(2)中那样从长度变为区域:

Quantity[_1 + _1] <<equal to>> Quantity[_2]

(很抱歉没有粘贴整个代码,这太过分了.我试图最小化我的例子,但我失败了.这就是为什么我只是链接到它.)

解决方法

MInt特征中缺少Subtractable类型Sub.当你想在MSucc和MNeg中减去一个类型时,一个简单的定义就是执行一个负增加.

sealed trait MInt extends Visitable[IntVisitor] with Addable with Subtractable {
  type AddType = MInt
  type SubType = MInt
  type Add[I <: MInt] <: MInt
  type Sub[I <: MInt] <: MInt
  type Neg <: MInt
  type Succ <: MInt
  type Pre <: MInt
}

final class _0 extends Nat {
  type Add[I <: MInt] = I
  type Sub[I <: MInt] = I#Neg
  type AcceptNatVisitor[V <: NatVisitor] = V#Visit0
  type Neg = _0
  type Succ = MSucc[_0]
  type Pre = Succ#Neg
}

final class MSucc[P <: Nat] extends Pos {
  type This = MSucc[P]
  type Add[N <: MInt] = P#Add[N]#Succ
  type Sub[N <: MInt] = Add[N#Neg]
  type AcceptNatVisitor[V <: NatVisitor] = V#VisitSucc[P]
  type Neg = MNeg[This]
  type Pre = P
  type Succ = MSucc[This]
}

final class MNeg[P <: Pos] extends MInt {
  type Add[N <: MInt] = P#Add[N#Neg]#Neg
  type Sub[N <: MInt] = Add[N#Neg]
  type Accept[V <: IntVisitor] = V#VisitNeg[P]
  type Neg = P
  type Succ = P#Pre#Neg
  type Pre = P#Succ#Neg
}

还有一件事,数量中的/方法应该划分它的参数而不是它们的乘法!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读