2014-02-17 59 views
19

我试图用我的方式理解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 
} 

这里我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 
} 

我可以看到它可能没有意义,我的类型继承类型,但肯定继承抽象类型。有没有在我的BoolType中定义AndImpl的方法,还是我必须在各自的TrueTypeFalseType特征中定义每个?

回答

10

您可以随时在你的布尔基本类型定义一个抽象类型如下:

trait MyBool extends BoolType{ 
    type This <: BoolType 
} 

trait TrueType extends BoolType{ 
    type This = TrueType 
} 

,你应该是好去与自己的参考。然后,你可以通过一个双重否定使用德摩根定律做以下

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

然后你就可以得到你And条件去:

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

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

+0

不要使用'This.Not'我会尝试使用This#Not'。你现在在类型层面工作。 – wheaties

+0

#FacePalm #MidnightPilotError #BeerThirty – joescii

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 
} 
+0

我喜欢这种方法,可以说不仅仅是创建一个'This'类型,因为它可以防止漏出。我一定会把这个变化推向前进,并在后续的帖子中记录下来。谢谢! – joescii

3

为什么不只是使用this关键字?当我自己探索类型级别的编程时,使用这个而不是自己时,我看不出有什么区别。

sealed trait BoolType { 
    type Not <: BoolType 
    type Or[That <: BoolType] <: BoolType 
    type And[That <: BoolType] = this.type#Not#Or[That#Not]#Not 
    type Imp[That <: BoolType] = this.type#Not#Or[That] 
} 
+0

我同意你的意见。事实上,一旦我将我的短途旅行编入一篇文章,我选择了这种确切的方法(没有双关语意思) – joescii

+1

我最近偶然发现了关于该主题的精彩博客系列。我将在本地聚会上介绍类型级编程。你的系列作为一个例子。所以感谢伟大的工作! – mavilein

+0

太棒了!我希望这会顺利!如果您需要任何额外帮助,请随时与我联系。 – joescii

相关问题