Valerin
Valerin

Reputation: 475

Scala: initializing vertexes of a graph

I have something like this:

def vertices: List[Vertex] = List()
def edges: List[Edge] = List()
def adjMatrix: Array[Array[Int]] = Array.ofDim[Int](vertices.size, vertices.size)
def addVertex(lbl: Char) = {
    val vertex = new Vertex(lbl)
     vertex :: vertices
     vertex
}
class Vertex(label: Char) {
  val visited: Boolean = false
  def echo() = print(label)
}

when I want to create nodes like this:

def main(args: Array[String]) {
    val node1 = g.addVertex('A')
    val node2 = g.addVertex('B')
    val node3 = g.addVertex('C')

    println(g.vertices.size) // the result is 0 ???!!!
}

I do not know why the list vertices isn't filled?

Upvotes: 0

Views: 168

Answers (1)

Gregor Raýman
Gregor Raýman

Reputation: 3081

It is because in the method:

def addVertex(lbl: Char) = {
    val vertex = new Vertex(lbl)
    vertex :: vertices // This does nothing
    vertex
}

You don't change the list vertices. You just produce a new list vertex :: vertices, but you throw it immediately away.

Please try changing the method to the following:

def addVertex(lbl: Char) = {
    val vertex = new Vertex(lbl)
    vertices = vertex :: vertices // This also changes the var vertices
    vertex
}

Also, the member vertices should be a var not a def returning always an empty list.

var vertices: List[Vertex] = List()

Here a variant of an immutable Graph:

case class Vortex(lbl: String)

case class Graph(vertices:Set[Vortex], edges:Set[(Vortex,Vortex)]) {
  def addVortex(vortex:Vortex) : Graph =
    Graph(vertices + vortex, edges)
  def addEdge(edge: (Vortex, Vortex)) : Graph =
    Graph(vertices + edge._1 + edge._2, edges + edge)
}

Upvotes: 1

Related Questions