I am modeling a DFA in Scala. I have a transition matrix which is a directed acyclic graph represented as 2-D matrix (more accurately, array or arrays). I have implemented a method getNextTransitions which will give me the possible next states based on the current state I am in. Consider the two implementations below which give correct output but differ in data structure used.
Using ListBuffer:
def getNextTransitions(currState: Int): List[Edge] = {
val ret: ListBuffer[Edge] = ListBuffer[Edge]()
val row: Array[Int] = transitionDAG(currState) //row is a 1-d array
row.indices.foreach(j => {
if (row(j) != -1) {
ret += Edge(STATES(currState), STATES(j), row(j))
}
})
ret.toList
}
Using List:
def getNextTransitions1(currState: Int): List[Edge] = {
var ret: List[Edge] = List[Edge]()
val row: Array[Int] = transitionDAG(currState) //row is a 1-d array
row.indices.foreach(j => {
if (row(j) != -1) {
ret = Edge(STATES(currState), STATES(j), row(j)) :: ret
}
})
ret
}
Scala encourages using immutable data structures, but I can't find a way of replacing var ret: List[Edge] with val ret: List[Edge] in getTransitions1 method above. Any suggestions?
Also, should I even try to force myself thinking in an alternative way when the getTransitions method using ListBuffer already does its job?
Adding definition of State and Edge classes. For the sake of simplicity, type parameters are removed in the question. So Edge class can be assumed to be case class Edge (start: State, end: State, edgeVal:Any)
State class:
case class State[+T](stateVal: T) {
override def toString: String = {
stateVal.toString
}
}
Edge class:
case class Edge[E](start: State[Any], end: State[Any], edgeVal: E) {
override def toString: String = {
start + " --" + edgeVal + "--> " + end
}
}