How to create a basic "Hello World" graph in Elixir

Graphs and graph databases are useful as they can address two main concerns in dealing with the vast volumes of data around us—organization and scale. Graphs can bring both order and growth to data as data goes large.

Elixir provides its users with built-in graph support. Erlang library digraph can be used, which is shipped with Elixir distribution to construct a graph in Elixir.

In this answer, we will explain how to create a "Hello World" graph. In this graph, we will have two vertices (i.e., "Hello" and "World") and one edge which connects these two vertices.

Let's see how to code the "Hello world" graph in Elixir.

Code

import :digraph
g = new()
v1 = add_vertex(g, "Hello")
v2 = add_vertex(g, "World")
add_edge(g, v1, v2)
IO.puts get_path(g, v1, v2)

Explanation

  1. line 1: Imports digraph library.

  2. line 3: Creates a new graph object.

  3. line 5-6: Adds 2 vertex to the graph. The first vertex is "Hello" and the second vertex added is "World".

  4. line 8: Creates an edge between v1 and v2 by using add_edge function.

  5. line 10: Path between v1 and v2 is displayed using get_path function.

Copyright ©2024 Educative, Inc. All rights reserved