Skip to content

Instantly share code, notes, and snippets.

@danilomo
Last active July 26, 2017 08:11
Show Gist options
  • Save danilomo/4f62e4a18558b69faa729cd2a6cf2993 to your computer and use it in GitHub Desktop.
Save danilomo/4f62e4a18558b69faa729cd2a6cf2993 to your computer and use it in GitHub Desktop.
Functional Graph API in Scala, using edge list as representation
/**
* A functional Graph object in Scala, for learning purposes.
*/
class Graph[V,W](val vertices: List[V], val edges: List[(V,V,W)]) {
override def toString(): String = vertices.toString() + ", " + edges.toString()
def addVertex(v: V): Graph[V,W] = Graph( v :: this.vertices, this.edges )
def addEdge(e: (V,V,W)): Graph[V,W] = Graph(this.vertices, e :: this.edges )
def neighbors( v: V ): List[V] = {
for((v1, v2, _) <- edges; if v == v1 ) yield v2
}
def weight( e: (V,V) ): W = {
val l = edges.filter( x => x._1 == e._1 && x._2 == e._2 )
l.head._3
}
def dfs( root: V ): List[V] ={
def dfs1_( v: V, discovered: Set[V]): List[V] = {
val dn = discovered + v
val n = neighbors(v).filter( ! discovered.contains(_))
n.flatMap( dfs1_( _ , dn) ) ::: List(v)
}
dfs1_( root, Set() ).distinct
}
}
object Graph{
def apply[V,W](vertices: List[V], edges: List[(V, V, W)]): Graph[V,W] = new Graph(vertices, edges)
def apply[V,W](vertices: List[V], edges: List[(V, V)], default: W): Graph[V,W]
= new Graph(vertices, for ( (a,b) <- edges ) yield (a, b, default))
}
object Main extends App{
val g = Graph[String, Double](
List( "S", "A", "B", "C", "D", "E", "F", "G" ),
List(
("S", "A"),
("S", "B"),
("S", "C"),
("A", "D"),
("B", "E"),
("C", "F"),
("D", "G"),
("E", "G"),
("F", "G")
), 1.0
)
g.dfs( "S" ).foreach( x => println( "Visited: " + x))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment