Erlang Digraph
Erlang has tons of goodies that most of people don’t know about. If you are studying IT just like me you should definitely learn digraph
, because you will have to implement a graph algorithm at some point and this can be considered real lifehack in such situations.
As you might have already guessed by the name it is a data structure that is used to store directed graphs in Erlang or Elixir. It is really easy to use. First thing you have to do is to actually initialize a graph.
If you run it in REPL you should get five element tupple with three #Reference<Something>
thingies. Don’t bother with what’s inside just for now.
After graph is successfuly initialized you can add vertices and edges.
Now you can for example find shortest road between two vertices.
Magic applied
Let’s write simple implementation of DFS. Depth-first search is a common algorithm of checking whether you can go from one vertex to rest of them. In my implementation it will just return list of visited vertices.
Runnable example available here.
Nitty gritty details
Rembember those three values I told you not to care about? It’s time to take a closer look at them.
First thing we should do to find enlightment is to look up how it is actually implemented in Erlang. In the digraph
module source we can find following lines:
It is quite similar to our tuple? If record is similar to struct where did the names go? Actually.. In Erlang records are bare tuples. The names exist only in compile time, after that they are gone. It is quite troublesome approach, but it clarifies a lot of what we can see right now. vtab
is first element, etab
is second and so forth and so on.
You might also have realized that all of the operations we performed previously were impure. That’s because digraph
is internally represented as set of three ets
tables and those weird #Reference
are actually results of creating new unnamed Erlang Term Storage
table.
What’s even more important we can actually see how it is internally represented! We can just call :ets.tab2list/1
and see how digraph manages it data.
We can see a lot of interesting information here. As we can see edges are actually numbered. Even more interesting is neighbours table which kind of resembles math notation of Neighbour relation.