I would like to model a simple graph where each node is connected to another node.
This seems like a reasonable definition of a node given the scenario:
case class Node(other: Node)
But say I want to create a graph that looks like this:
--------------
| |
node_a V
^ node_b
| |
--------------
It appears impossible to create such a graph given the definition of Node
because other
is immutable and needs to be assigned on creation but it is impossible to create both nodes at the same time.
I suppose I could just store the name of the other node:
case class Node(name: String, otherName: String)
...
val n1 = Node("a", "b")
val n2 = Node("b", "a")
val nodes = Map(n1.name -> n1, n2.name -> n2)
This requires an additional step of generating a unique identifier per node. It's not terrible, but I really like the elegance of traversing the graph directly using the nodes themselves, a la n.other
instead of nodes.get(n.other)
.
Am I searching for the impossible here?