我想用a preceding question的答案來實現一個小圖庫。這個想法是考慮圖形作爲集合,其中頂點包裝集合元素。我想使用抽象類型來表示Vertex和Edge類型(因爲類型安全),我想使用類型參數來表示集合元素的類型(因爲我想在實例化中很容易定義它們)。在scala中混合類型參數和抽象類型
但是,當嘗試我能想到的最基本的例子時,我遇到了編譯錯誤。這裏是例子:
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]
我只得到第一個錯誤。)
你有什麼想法嗎?
您能否說明您爲什麼要將圖表作爲集合? – 2010-01-14 19:42:47
這個庫的一個應用是在圖上實現一種細胞自動機(另一個是複雜的網絡研究)。然後,直接訪問頂點中包含的Cell對象可能會更好......但如果您對解決方案沒有圖形作爲集合功能的想法,我也很感興趣。 – paradigmatic 2010-01-14 20:00:05
我仍然不確定是否看到連接。您如何看待圖形庫與JGraphT的區別?它是一種圖形的功能方法嗎? – 2010-01-14 20:53:47