soc*_*soc 6 generics alias types scala units-of-measurement
我在使用metascala中的度量单位功能时遇到了问题,该功能在Units.scala文件中定义.
对于本问题的其余部分,我将使用简化方案,只有一种单位类型,长度.
所以现实中的类型看起来像
Quantity[_1, _0, _0, _0, _0, _0, _0]
^ ^ ^ ^ ^ ^ ^
| | | | | | |
| Mass | Crncy.| Mol |
Length Time Temp. Lum.Intensity
Run Code Online (Sandbox Code Playgroud)
这足以证明问题:
Quantity[_1]
^
|
Length
Run Code Online (Sandbox Code Playgroud)
一旦需要推断出类型,麻烦就开始了.
考虑这个例子(也看看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!
Run Code Online (Sandbox Code Playgroud)
我在最后一行收到错误说:
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
]
Run Code Online (Sandbox Code Playgroud)
看起来编译器无法弄清楚手头的类型是否等于Quantity[_1]"减去一个维度",例如从一个区域到另一个区域,如(1):
Quantity[_2 - _1] <<not equal to>> Quantity[_1]
Run Code Online (Sandbox Code Playgroud)
令人困惑的是,它在"添加维度"时起作用,例如从长度到区域,如(2):
Quantity[_1 + _1] <<equal to>> Quantity[_2]
Run Code Online (Sandbox Code Playgroud)
(很抱歉没有粘贴整个代码,这太过分了.我试图最小化我的例子,但我失败了.这就是为什么我只是链接到它.)
特征中缺少Subfrom类型。使它起作用的一个简单定义是,当您想要减去和中的类型时,执行负加法。SubtractableMIntMSuccMNeg
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
}
Run Code Online (Sandbox Code Playgroud)
还有一件事,/中的方法Quantity应该将其参数相除而不是相乘!