`this`关键字的Scala类型编程类比是什么?

joe*_*cii 19 types scala metaprogramming

我正在努力学习Scala中的类型编程,并且我发现大多数关于类型编程需要知道的东西在值编程中都有类似的对应关系,这反映在类型级编程维基页面中.但是,我没有找到this关键词或自我类型的类比.我怀疑期待这样的事情可能没有意义,但我想我会问.

例如,我可以编写以下代码来表示Booleans在运行时的值:

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
}
Run Code Online (Sandbox Code Playgroud)

这里我andimp能够利用的事实,如果我是一个错误的对象或真实对象进行正确定义不要紧优势.我TrueValFalseVal对象可以继承相同的代码.

我可以制作类似的类型级编程结构,但我不明白如何定义AndImp我的基本特征.

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
}
Run Code Online (Sandbox Code Playgroud)

我可以看到我的类型继承类型可能没有意义,但肯定会继承抽象类型.有没有办法定义AndImpl在我的BoolType,或者我必须在各自TrueTypeFalseType特征中定义每个?

whe*_*ies 10

您始终可以在布尔基类型上定义抽象类型,如下所示:

trait MyBool extends BoolType{
  type This <: BoolType
}

trait TrueType extends BoolType{
  type This = TrueType
}
Run Code Online (Sandbox Code Playgroud)

你应该善于引用自己.然后您可以使用DeMorgan的法律来执行以下操作

 !(x && y) == (!x || !y)
Run Code Online (Sandbox Code Playgroud)

然后通过双重否定你可以让你的And条件:

 !(!x || !y) == !!(x && y) == (x && y)
Run Code Online (Sandbox Code Playgroud)

  • DeMorgan就像我在"BoolVal"特质中所拍摄的一样.但是......我尝试了你的建议,但它没有编译.特别是,`And`和`Imp`的定义没有编译:`type和[That <:BoolType] = This.Not.Or [That.Not] .Not`和`type Imp [That <:BoolType ] = This.Not.Or [那]` (2认同)

EEC*_*LOR 9

我建议使用self,调整你的博客文章的例子:

sealed trait BoolType { self =>
  type Not <: BoolType
  type Or[That <: BoolType] <: BoolType
  type And[That <: BoolType] = self.type#Not#Or[That#Not]#Not
  type Imp[That <: BoolType] = self.type#Not#Or[That]
}
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
}
Run Code Online (Sandbox Code Playgroud)