Elixir Libraries

Welcome to a tutorial on Libraries in Elixir.

Excellent interoperability with Erland libraries is provided by Elixir. we will look at some Elixir libraries in the next session of this tutorial.

 

The Binary Module

Binaries that are UTF-8 encoded are handled by the built-in Elixir String module. This binary module is quite useful when dealing with binary data that is not necessarily UTF-8 encoded. Check out the example below.

# UTF-8
IO.puts(String.to_char_list("Ø"))

# binary
IO.puts(:binary.bin_to_list "Ø")

The output is:

[216]
[195, 152]

The example above, shows the difference, as the String module returns UTF-8 codepoints, while :binary deals with raw data bytes.

 

The Crypto Module

In Elixir, the crypto module contains hashing functions, digital signatures, encryption, etc. This module is not part of the Erlang standard library, however, it is included with the Erlang distribution, meaning that you must list :crypto in your project’s applications list whenever you use it. Check out the example below.

IO.puts(Base.encode16(:crypto.hash(:sha256, "Elixir")))

The output is:

3315715A7A3AD57428298676C5AE465DADA38D951BDFAC9348A8A31E9C7401CB

 

The Digraph Module

In Elixir, the digraph module contains functions for dealing with directed graphs built of vertices and edges. After constructing the graph, the algorithms there helps in finding, for instance, the shortest path between two vertices, or loops in the graph. Take note that the functions :digraph alter the graph structure indirectly as a side effect while returning the added vertices or edges. Check out the example below.

digraph = :digraph.new()
coords = [{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}]
[v0, v1, v2] = (for c <- coords, do: :digraph.add_vertex(digraph, c))
:digraph.add_edge(digraph, v0, v1)
:digraph.add_edge(digraph, v1, v2)
for point <- :digraph.get_short_path(digraph, v0, v2) do 
   {x, y} = point
   IO.puts("#{x}, #{y}")
end

The output is:

0.0, 0.0
1.0, 0.0
1.0, 1.0

 

The Math Module

In Elixir, the math module contains common mathematical operations covering trigonometry, exponential and logarithmic functions. Check the example below.

# Value of pi
IO.puts(:math.pi())

# Logarithm
IO.puts(:math.log(7.694785265142018e23))

# Exponentiation
IO.puts(:math.exp(55.0))

#...

The output is:

3.141592653589793
55.0
7.694785265142018e23

 

The Queue Module

In Elixir, the queue is a data structure that implements (double-ended) FIFO (first-in-first-out) queues efficiently. Check out the example below.

q = :queue.new
q = :queue.in("A", q)
q = :queue.in("B", q)
{{:value, val}, q} = :queue.out(q)
IO.puts(val)
{{:value, val}, q} = :queue.out(q)
IO.puts(val)

The output is:

A
B