Advertisement
Guest User

Untitled

a guest
Jul 21st, 2014
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.57 KB | None | 0 0
  1. /**
  2.  * A basic graph trait, with a Node type and an EdgeData type (used to form the triple (Node, Node, EdgeData))
  3.  * @tparam Node The type of the nodes in the graph
  4.  * @tparam EdgeData The data associated with a particular edge between two nodes.
  5.  */
  6. trait Graph[Node, EdgeData] {
  7.   type Edge = (Node, Node, EdgeData)
  8.  
  9.   def addNode(node: Node): Graph[Node, EdgeData]
  10.   val nodes: List[Node]
  11.  
  12.   def addEdge(n1: Node, n2: Node, dat: EdgeData): Graph[Node, EdgeData]
  13.   val edges: List[Edge]
  14. }
  15.  
  16. /**
  17.  * An extension of the graph trait, where each node is itself a graph.
  18.  *
  19.  * @tparam Node The type of the nodes in the graph (which itself must be a graph)
  20.  * @tparam EdgeData The data associated with a particular edge between two nodes
  21.  */
  22. trait RecursiveGraph[Node <: RecursiveGraph[Node, EdgeData], EdgeData] extends Graph[Node, EdgeData]
  23.  
  24. /**
  25.  * A simple implementation of an immutable graph
  26.  * @tparam Node The type of the nodes in the graph
  27.  * @tparam EdgeData The data associated with a particular edge between two nodes.
  28.  */
  29. sealed class ImmutableGraph[Node, EdgeData] extends Graph[Node, EdgeData] {
  30.   outer: ImmutableGraph[Node, EdgeData] =>
  31.  
  32.   val nodes = List.empty[Node]
  33.   val edges = List.empty[Edge]
  34.  
  35.   final def addNode(node: Node) = new ImmutableGraph[Node, EdgeData] {
  36.     override val nodes = node :: outer.nodes
  37.     override val edges = outer.edges
  38.   }
  39.  
  40.   final def addEdge(n1: Node, n2: Node, dat: EdgeData) = new ImmutableGraph[Node, EdgeData] {
  41.     override val nodes = outer.nodes
  42.     override val edges = (n1, n2, dat) :: outer.edges
  43.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement