【发布时间】:2018-06-08 14:20:42
【问题描述】:
我有类型级算术的实现,能够进行一些编译时算术验证,即<,>,=,有两种方式:
有了这些,我可以有一个 getFoo 函数,我可以这样调用:
getFoo[_2,_3]
_2 和 _3 是整数值 2 和 3 的类型级等价物。现在理想情况下,我希望我的 getFoo 函数将整数值作为参数并尝试从值推断 _2 2.
我的计划是将以下 associatedInt 信息添加到 Nat 基类:
trait Nat {
val associatedInt: Int
type AssociatedInt = associatedInt.type
}
这样后续的类型会被定义为:
type _1 = Succ[_0] {
override val associatedInt: Int = 1
}
然后将getFoo的签名改成整数:
def getFoo(i:Int)(implicit ...)
基于此,我们将使用与AssociatedInt 类型关联的类型进行类型级别的算术断言。即,类似:
def getFoo(i: Integer)(implicit ev: Nat{type I = i.type } =:= ExpectedType)
这不起作用。即:
trait Nat {
val i: Integer
type I = i.type
}
type ExpectedType = _1
trait _1 extends Nat {
override val i: Integer = 1
}
def getFoo(i: Integer)
(implicit ev: Nat{type I = i.type } =:= ExpectedType)= ???
getFoo(1) //this fails to prove the =:= implicit.
回想起来,我不应该期望它。因为如果我们有:
val x : Integer = 1
val y : Integer = 1
type X = x.type
type Y = y.type
def foo(implicit ev: X =:= Y) = 123
foo //would fail to compile.
即具有相同值的不同“对象”的单例类型是不同的。 (我猜原因是目前在 Scala 中,单例类型用于对象,与 literal type 不同)
因此,有了这些背景信息,我想知道是否有任何方法可以实现我想要做的事情,即通过其他方法从关联值推断 a 类型。
【问题讨论】:
标签: scala types type-deduction type-level-computation type-variables