我试图用我的方式理解Scala中的类型编程,并且我发现大多数关于类型编程需要知道的东西在编程中有一个类似的对应部分,如the type-level programming wiki page中所反映的。但是,我还没有找到关键字或自我类型的类比。我怀疑也许期望这样的事情没有意义,但我想我会问。什么是`this`关键字的Scala类型编程类比?
举例来说,我可以写出如下表示布尔值作为运行时间值:
sealed trait BoolVal {
def not:BoolVal
def or(that:BoolVal):BoolVal
def and(that:BoolVal) =
(this.not or that.not).not
def imp(that:BoolVal) =
this.not or that
}
case object TrueVal extends BoolVal {
override val not = FalseVal
override def or(that:BoolVal) = TrueVal
}
case object FalseVal extends BoolVal {
override val not = TrueVal
override def or(that:BoolVal) = that
}
这里我and
和imp
能够利用的事实,这并不重要,如果我是一个错误的对象或一个真正的对象被正确定义。我的TrueVal
和FalseVal
对象可以继承相同的代码。
我可以制作类似级别的编程结构,但我不明白如何在我的基本特征中定义And
和Imp
。
sealed trait BoolType {
type Not <: BoolType
type Or[That <: BoolType] <: BoolType
type And[That <: BoolType] = ???
type Imp[That <: BoolType] = ???
}
sealed trait TrueType extends BoolType {
override type Not = FalseType
override type Or[That <: BoolType] = TrueType
}
sealed trait FalseType extends BoolType {
override type Not = TrueType
override type Or[That <: BoolType] = That
}
我可以看到它可能没有意义,我的类型继承类型,但肯定继承抽象类型。有没有在我的BoolType
中定义And
和Impl
的方法,还是我必须在各自的TrueType
和FalseType
特征中定义每个?
DeMorgan's正是我所拍摄的像我的'BoolVal'特性。但是......我尝试了你的建议,但它却没有编译。特别是'And'和'Imp'的定义没有编译:'type And [That <:BoolType] = This.Not.Or [That.Not] .Not' and'type Imp [That <:BoolType ] = This.Not.Or [That]' – joescii
不要使用'This.Not'我会尝试使用This#Not'。你现在在类型层面工作。 – wheaties
#FacePalm #MidnightPilotError #BeerThirty – joescii