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

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

发布时间:2020-12-16 09:39:34 所属栏目:安全 来源:网络整理
导读:我正在努力学习Scala中的类型编程,并且发现大多数需要了解类型编程的内容与 the type-level programming wiki page中反映出来的价值编程类似。但是,没有找到这个关键词或自我类型的类比。我怀疑也许没有理由期待这样的事情,但我以为我会问。 例如,我可以
我正在努力学习Scala中的类型编程,并且发现大多数需要了解类型编程的内容与 the type-level programming wiki page中反映出来的价值编程类似。但是,没有找到这个关键词或自我类型的类比。我怀疑也许没有理由期待这样的事情,但我以为我会问。

例如,我可以在运行时写下面的代表布尔值作为值:

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
}

这里我和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特征中定义每个?

解决方法

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

trait MyBool extends BoolType{
  type This <: BoolType
}

trait TrueType extends BoolType{
  type This = TrueType
}

你应该很好去参考自己。那么您可以使用DeMorgan的法律来执行以下操作

!(x && y) == (!x || !y)

然后一个双重的负面你可以得到你和条件去:

!(!x || !y) == !!(x && y) == (x && y)

(编辑:李大同)

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

    推荐文章
      热点阅读