我正在尝试使用之前的问题的答案来实现一个小型图形库。想法是将图形视为集合,其中顶点包装集合元素。
我希望使用抽象类型来表示顶点和边缘类型(因为需要类型安全),并且我想使用类型参数来表示集合元素的类型(因为我希望在实例化时轻松定义它们)。
但是,当我尝试最基本的示例时,我遇到了编译错误。以下是示例:
我希望使用抽象类型来表示顶点和边缘类型(因为需要类型安全),并且我想使用类型参数来表示集合元素的类型(因为我希望在实例化时轻松定义它们)。
但是,当我尝试最基本的示例时,我遇到了编译错误。以下是示例:
package graph
abstract class GraphKind[T] {
type V <: Vertex[T]
type G <: Graph[T]
def newGraph(): G
abstract class Graph[T] extends Collection[T]{
self: G =>
def vertices(): List[V]
def add(t: T): Unit
def size(): Int
def elements(): Iterator[T]
}
trait Vertex[T] {
self: V =>
def graph(): G
def value(): T
}
}
以下是基本实现:
class SimpleGraphKind[T] extends GraphKind[T] {
type G = GraphImpl[T]
type V = VertexImpl[T]
def newGraph() = new GraphImpl[T]
class GraphImpl[T] extends Graph[T] {
private var vertices_ = List[V]()
def vertices = vertices_
def add( t: T ) { vertices_ ::= new VertexImpl[T](t,this) }
def size() = vertices_.size
def elements() = vertices.map( _.value ).elements
}
class VertexImpl[T](val value: T, val graph: GraphImpl[T]) extends Vertex[T] {
override lazy val toString = "Vertex(" + value.toString + ")"
}
}
编译时,我遇到了以下问题:
/prg/ScalaGraph/study/Graph.scala:10: error: illegal inheritance;
self-type GraphKind.this.G does not conform to Collection[T]'s selftype Collection[T]
abstract class Graph[T] extends Collection[T]{
^
/prg/ScalaGraph/study/Graph.scala:33: error: illegal inheritance;
self-type SimpleGraphKind.this.GraphImpl[T] does not conform to SimpleGraphKind.this.Graph[T]'s selftype SimpleGraphKind.this.G
class GraphImpl[T] extends Graph[T] {
^
/prg/ScalaGraph/study/Graph.scala:36: error: type mismatch;
found : SimpleGraphKind.this.VertexImpl[T]
required: SimpleGraphKind.this.V
def add( t: T ) { vertices_ ::= new VertexImpl[T](t,this) }
^
/prg/ScalaGraph/study/Graph.scala:38: error: type mismatch;
found : Iterator[T(in class SimpleGraphKind)]
required: Iterator[T(in class GraphImpl)]
def elements() = vertices.map( _.value ).elements
^
/prg/ScalaGraph/study/Graph.scala:41: error: illegal inheritance;
self-type SimpleGraphKind.this.VertexImpl[T] does not conform to SimpleGraphKind.this.Vertex[T]'s selftype SimpleGraphKind.this.V
class VertexImpl[T](val value: T, val graph: GraphImpl[T]) extends Vertex[T] {
^
5 errors found
我完全不知道这些错误的含义... 但是,如果我在实现中专门指定类型T(class SimpleGraphKind extends GraphKind [Int]
),我只会得到第一个错误。
你有什么想法吗?
vertex1.connectTo(vertex2)
或vertex1 -> vertex2
而不是graph.connect(vertex1, vertex2)
)。顶点可以包含逻辑,也可以只是图对象的代理,具体取决于实现方式。 - paradigmatic