Elixir - Libraries


Advertisements

Elixir provides excellent interoperability with Erlang libraries. Let us discuss a few libraries in brief.

The Binary Module

The built-in Elixir String module handles binaries that are UTF-8 encoded. The binary module is useful when you are dealing with binary data that is not necessarily UTF-8 encoded. Let us consider an example to further understand the Binary module −

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

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

When the above program is run, it produces the following result −

[216]
[195, 152]

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

The Crypto Module

The crypto module contains hashing functions, digital signatures, encryption and more. This module is not part of the Erlang standard library, but is included with the Erlang distribution. This means you must list :crypto in your project’s applications list whenever you use it. Let us see an example using the crypto module −

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

When the above program is run, it produces the following result −

3315715A7A3AD57428298676C5AE465DADA38D951BDFAC9348A8A31E9C7401CB

The Digraph Module

The digraph module contains functions for dealing with directed graphs built of vertices and edges. After constructing the graph, the algorithms in there will help finding, for instance, the shortest path between two vertices, or loops in the graph. Note that the functions in :digraph alter the graph structure indirectly as a side effect, while returning the added vertices or edges.

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

When the above program is run, it produces the following result −

0.0, 0.0
1.0, 0.0
1.0, 1.0

The Math Module

The math module contains common mathematical operations covering trigonometry, exponential and logarithmic functions. Let us consider the following example to understand how the Math module works −

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

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

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

#...

When the above program is run, it produces the following result −

3.141592653589793
55.0
7.694785265142018e23

The Queue Module

The queue is a data structure that implements (double-ended) FIFO (first-in first-out) queues efficiently. The following example shows how a Queue module works −

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)

When the above program is run, it produces the following result −

A
B
Advertisements