Noob到scala路径依赖类型
我不清楚如何在下面的代码片段中实现路径依赖类型。目的是能够使用“meld”方法合并两个堆。AFAIK需要路径依赖类型 这就是特点Noob到scala路径依赖类型,scala,traits,path-dependent-type,Scala,Traits,Path Dependent Type,我不清楚如何在下面的代码片段中实现路径依赖类型。目的是能够使用“meld”方法合并两个堆。AFAIK需要路径依赖类型 这就是特点 trait Heap { type H // type of a heap type A // type of an element def ord: Ordering[Heap#A] // ordering on elements def meld(h1: Heap#H, h2: Heap#H): Heap#H // the heap resulti
trait Heap {
type H // type of a heap
type A // type of an element
def ord: Ordering[Heap#A] // ordering on elements
def meld(h1: Heap#H, h2: Heap#H): Heap#H // the heap resulting from merging h1 and h2
..
}
下面是实现的一部分
class HeapImpl extends Heap {
override type H = HeapImpl // this.type
override type A = Integer
..
// the heap resulting from inserting x into h
override def meld(h1: Heap#H, h2: Heap#H): Heap#H = {
while (!isEmpty(h2)) {
insert(deleteMin(h2),h1)
}
this
}
meld方法上的返回值“this”出现编译错误:
Expression HeapImpl does not conform to expected type Heap#H
在HeapImpl
中,H
只是HeapImpl
,返回类型将符合
这样,方法中的A
和H
与类型中定义的相同…
。路径相关类型意味着您可以编写类似于heap.A
(其中heap
是heap
)的类型
我还要注意,您的meld
实现看起来很奇怪。看起来您正在将h2
的元素插入h1
(如果不是,插入insert
的第二个参数是什么意思?),但是,您没有返回h1
,而是返回this
在HeapImpl
中,H
只是HeapImpl
,返回类型将符合
这样,方法中的A
和H
与类型中定义的相同…
。路径相关类型意味着您可以编写类似于heap.A
(其中heap
是heap
)的类型
我还要注意,您的meld
实现看起来很奇怪。看起来您正在将h2
的元素插入h1
(如果不是,插入insert
的第二个参数是什么意思?),但是,您没有返回h1
,而是返回this
在HeapImpl
中,H
只是HeapImpl
,返回类型将符合
这样,方法中的A
和H
与类型中定义的相同…
。路径相关类型意味着您可以编写类似于heap.A
(其中heap
是heap
)的类型
我还要注意,您的meld
实现看起来很奇怪。看起来您正在将h2
的元素插入h1
(如果不是,插入insert
的第二个参数是什么意思?),但是,您没有返回h1
,而是返回this
在HeapImpl
中,H
只是HeapImpl
,返回类型将符合
这样,方法中的A
和H
与类型中定义的相同…
。路径相关类型意味着您可以编写类似于heap.A
(其中heap
是heap
)的类型
我还要注意,您的meld
实现看起来很奇怪。看起来您正在将h2
的元素插入h1
(如果不是,插入insert
的第二个参数是什么意思?),但是,您没有返回h1
,而是返回this
投影堆#H与此不同
scala> trait Heap { type H ; type A ; def m(h1: H, h2: H): H }
defined trait Heap
scala> class Impl extends Heap { type H = Impl; def m(h1: H, h2: H) = this }
defined class Impl
投影堆#H与此不同
scala> trait Heap { type H ; type A ; def m(h1: H, h2: H): H }
defined trait Heap
scala> class Impl extends Heap { type H = Impl; def m(h1: H, h2: H) = this }
defined class Impl
投影堆#H与此不同
scala> trait Heap { type H ; type A ; def m(h1: H, h2: H): H }
defined trait Heap
scala> class Impl extends Heap { type H = Impl; def m(h1: H, h2: H) = this }
defined class Impl
投影堆#H与此不同
scala> trait Heap { type H ; type A ; def m(h1: H, h2: H): H }
defined trait Heap
scala> class Impl extends Heap { type H = Impl; def m(h1: H, h2: H) = this }
defined class Impl