Mixing type parameters and abstract types in scala

后端 未结 2 1777
野趣味
野趣味 2021-02-08 16:57

I am trying to use the answer of a preceding question to implement a small graph library. The idea is to consider graphs as colections, where vertices wrap collection elements.<

2条回答
  •  终归单人心
    2021-02-08 17:58

    It seems that Vertex's belonging to a particular graph and only that graph can be represented best in the type system with a nested Vertex trait in the Graph. Is what you are trying to achieve met with the following structure?

    abstract class Graph[T] extends Collection[T] {
      thisGraph: Graph[T] =>
    
      def newGraph: Graph[T] 
      def vertices: List[Vertex[T]]
      def add(t: T): Unit
      def size: Int
      def elements: Iterator[T]
    
      trait Vertex[T] {
          def graph = thisGraph
          def value: T
      }
    }
    
    class SimpleGraph[T] extends Graph[T] {
      private[this] var verts = List[Vertex[T]]()
    
      def newGraph = new SimpleGraph[T]
      def vertices = verts
      def add(t: T) { verts ::= SimpleVertex(t) }
      override def size = verts.size
      override def elements = verts.map(_.value).elements
      def iterator = elements // the "new" elements in 2.8
    
      case class SimpleVertex[T](value: T) extends Vertex[T]
    }
    

提交回复
热议问题