পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Monday, January 30, 2017

Elixir - Libraries

Elixir provides excellent interoperability with Erlang libraries. Let us have a look at some of these libraries.

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 look at an example:
# UTF-8
IO.puts(String.to_char_list("Ø"))

# binary
IO.puts(:binary.bin_to_list "Ø")
When running above program, it produces 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. The :crypto 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 use see an example using the crypto module:
IO.puts(Base.encode16(:crypto.hash(:sha256, "Elixir")))
When running above program, it produces 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 running above program, it produces 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 look at some examples:
# Value of pi
IO.puts(:math.pi())

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

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

#...
When running above program, it produces 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. Let us look at an example:
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 running above program, it produces following result:
A
B

No comments:

Post a Comment