"Introduction to Elixir" — the first book in the Elixir in Russian

Introduction to Elixir It happened suddenly, but brought a lot of joy. Finally publishing house drew attention to the interest of developers to Elixir and released the first book on this language in Russian. The choice of newspaper to transfer the expected is material for people who want to become familiar with the language or have already started to learn and ready to learn about more opportunities.

Elixir — dynamic, functional programming language designed for building scalable and easily maintainable applications. Based on the Erlang VM, effective for distributed, fault-tolerant systems with low latency at the same time successfully used in web development and embedded SOFTWARE.



"Introduction to Elixir" — a standard representative of the literature on programming languages. The story is told sequentially, from basic syntax to advanced modules and techniques. Examples of synthetic, but illustrate the text so that it becomes immediately clear what was going on. Given that the language is expressive, and a set of tools inherited from erlang is impressive, it's never boring.

Next, review each of the chapters in more detail.

the

Chapter 1. Get comfortable


Here everything is standard. Preparing to work with the language, explaining the basics and a short master class on work with an interactive shell.

the

Chapter 2. Functions and modules


After 20 minutes of work with the book, we are already familiar with the basic charm and beauty of the language function. It would seem, nothing unusual, just one of the elements of the language. But in fact, functions in Elixir — it is the Foundation.

And here are the first reveals unusual features of the language. For example, the Association functions through the pipes when this design

the
Enum.map(List.flatten([1, [2], 3]), fn x - > x * 2 end)

transformed into elegant,

the
[1, [2], 3]
|> List.flatten 
|> Enum.map(fn x - > x * 2 end)

Or how about this feature? Adding comments to the functions you can obtain the full documentation built into the language means.

the

Chapter 3. Atoms, tuples, and pattern matching


Experience with the book depends on what languages you already know. If you have not previously experienced with functional languages or are not familiar with the syntax of ruby, then this will start revelations.

First, in the Elixir data type is atom. I really like elements of this type have a value that matches the name.

the
iex(1)>: test
:test

But such a simple idea in a significant way (if you are using other language mechanisms) influence the style of programming in Elixir.

the
defmodule Drop do
def fall_velocity (earth, distance) do
:math.sqrt(2 * 9.8 * distance)
end

def fall_velocity(:moon, distance) do
:math.sqrt(2 * 1.6 * distance)
end

def fall_velocity(:mars, distance) do
:math.sqrt(2 * 3.71 * distance)
end 
end

For example, here is overridden the same function three times. This is actually 3 different functions, each of which can be selected using the pattern matching the first argument of the atom.

This is the basic technique language, which can do wonders. And the book tells how to do it. Whether using guard conditions or more complex than usual, atoms, comparison with the sample.

the

Chapter 4. Logic and recursion


Programs in functional languages accepted to write more with recursion than using standard cycles. About how to write a recursion that will be able to optimize the compiler, read this Chapter. Thanks to pattern matching, which is used in the guard conditions and Boolean expressions, recursion turns out very elegant and unusual.
the
defmodule Fact do
def factorial(n) do 
factorial(1, n, 1)
end

defp factorial(current, n, result) when current <= n do
new_result = result * current
IO.puts("#{current} yields #{new_result}.") factorial(current + 1, n, new_result)
end

defp factorial(_current, _n, result) do
IO.puts("Finished!")
result
end
end


the

Chapter 5. Human interaction


One of the major technical differences of the Elixir from erlang is to complete the processing mechanism of the strings. Now this is not just a list of characters, and a full binary data type that can support Unicode. And thanks to the lines we can interact with the user.

the

Chapter 6. Lists


I Hope that I can awaken in you the interest in the language. Apart from the interesting syntactic features and cool ideas at the core, everything works amazingly fast. Not for nothing, the Elixir compared for speed with Go and Rust, and speed development with ruby.


Elixir has excellent support for lists, long series of values. They help to assess the merits of recursion and allow you to perform large volume of work with minimal effort. Though it is a standard data type for functional languages, there is something to talk about.

the

defmodule Pascal do
def add_row(initial) do
add_row(initial, 0, [])
end

def add_row([], 0, nal) do
[0 | nal]
end

def add_row([h | t], last, new) do
add_row(t, h, [last + h | new])
end
end

Here is functional programming with a human face.

the

Chapter 7. Pair name/value


I sometimes ask. Once the Elixir is no object, then how are we supposed to work with structured data? Tuples and lists are nice but they don't allow you to get a value by name. Elixir, though young, but already Mature (production ready language). Therefore, the developers have provided mechanisms to address this problem. In Elixir there are types of data where you can retrieve the value by key. And this Chapter is dedicated to them — from dictionary to structure.

the

Chapter 8. Higher-order functions and generators of lists


Higher-order functions, or functions that take arguments of other functions, help the Elixir to manifest in all its brilliance. Not to say that in other languages it is impossible to realize such function, it is possible in almost any language, but in the Elixir of a higher-order function is interpreted as a natural part of the language, and not as artificial and alien education.

Not the most exciting Chapter, but learn about these opportunities will not be superfluous.

the

Chapter 9. Processes


If you have good programming experience, until now you could be boring. I hasten to please you, the most interesting thing about the killer features of the Elixir starts right now!


In the description of the Elixir as benefits usually mention some processes. They say that they allow you to achieve distribution, increase the speed of the program used in the scaling and hot swapping of code, but it is not clear what they represent and how to look within the language itself.

In fact, the process is another organizational unit of the program, along with functions and modules, which is an independent component, able to receive and send messages. A running program is a set of processes.

Starts the conversation in this Chapter, the interactive shell, which is also a process. The processes stated in great detail, and also discusses additional tools for working with them.

the

Chapter 10. Exceptions, errors and debugging


With debugging in Elixir is not all roses, as there are no fully native tools. Most popular — Pry (from ruby) and :dbg (erlang). In fact, they are quite comfortable to use, and the book provides a good analysis of the second of them.

the

Chapter 11. Static analysis, type specifications and testing


In programming there are three main classes of errors: syntax errors, run-time errors, and semantic errors. The Elixir compiler detects and reports syntax errors. Remain logical errors when you require one Elixir, having something else in mind. Logging and tracing can help in finding such errors, but it's better to try to prevent them from the beginning. And this will help the static analysis, type specifications and unit testing. All this is told in this Chapter.
Elixir has a very non-trivial possibilities in these areas. For example, the built-in documentation tests:

the

defmodule Drop do
@doc """
Calculates the speed of a falling object on the specified object 
planemo (the object with planetary mass)

iex(1)> Drop.fall_velocity(:earth, 10) 
14.0

iex(2) > Drop.fall_velocity(:mars, 20) 
12.181953866272849

iex> Drop.fall_velocity(:jupiter, 10)
** (CaseClauseError) no case clause matching: :jupiter
"""

def fall_velocity(planemo, distance) do 
gravity = case planemo do
:earth - > 9.8
:moon -> 1.6 
:mars - > 3.71
end

:math.sqrt(2 * gravity * distance) 
end
end

Now, you can be confident that the documentation will always be up to date!

the

Chapter 12. Storing structured data


As much as we wanted to have a pure function, in practice this is impossible, because the data need to be stored somewhere. To do this, erlang has a bunch of built-in tools, which fortunately you can benefit from the Elixir. This Chapter examines ETS and Mnesia.

Just imagine that you no longer need the Radish, as external dependencies. After all, his "replacement" built right into the language and is supported out of the box.

the

Chapter 13. The basics of OTP


Everyone that comes into the world of erlang and Elixir, you hear about a certain OTP, which is discussed more experienced colleagues. The subcortex is delayed, that is some very cool stuff, incredibly useful and simple thanks to daily development. But what is absolutely not clear.

It turns out that OTP is a framework for writing raspredelennykh and highly reliable applications. It uses all the chips of the virtual machine of erlang, and allows programmers to think only about the business logic, not the implementation details.

The most popular modules are GenServer and Supervisor. They look like this:

the

defmodule DropServer do
use GenServer

defmodule State do
defstruct count: 0
end

def start_link do
GenServer.start_link(__MODULE__, [], [{:name, __MODULE__}])
end

def init([]) do
{:ok, %State{}}
end

def handle_call(request, _from, state) do 
distance = request
reply = {ok, fall_velocity(distance)} 
new_state = %State{count: state.count + 1} 

{:reply, reply, new_state}
end

def handle_cast(_msg, state) do
IO.puts("So far, calculated #{state.count} velocities.") 

{:noreply, state}
end

def handle_info(_info, state) do
{:noreply, state}
end

def terminate(_reason, _state) do
{:ok}
end

def code_change(_old_version, state, _extra) do 
{:ok, state}
end

def fall_velocity(distance) do
:math.sqrt(2 * 9.8 * distance)
end
end

To learn more about them you can here and here. Or in the current Chapter of the book.

And Elixir offers thing, the dream of all erlangeri — utility Mix.
Her review is also in the book.

the

Chapter 14. The language extension Elixir using macros


Another feature that distinguishes Elixir from erlang — advanced metaprogramming. It is implemented through the creation of macros. Externally, the macros are very similar in function, differing only in that starts with the statement defmacro is def. However, the macros are quite different than functions. This allows you to create a cool DSL, not usuauy rubislaw.

the

Chapter 15. Phoenix


Well, the book concludes such an important topic as the Phoenix. It is a web framework and want to compare with Rails. Phoenix inherited the rails philosophy and some of the approaches, although it is now gradually extended to his side. But we should note that the Phoenix is the same engine for the Elixir, and at the time, Rails for ruby.

An introductory course on Phoenix you can read in the book or this series, which I translate for Habra.

the

Insights


The book is exceptionally good. I have a few months make a project and Wunsch, where we familiarise the readers with a beautiful Elixir. And I still was interested to read the book, I managed to draw the nuances when working with familiar parts of the language and to learn about other options that had not previously encountered.

the text placed links to interesting articles on the Elixir, which we translate in the framework of Wonsa. If you want weekly to obtain useful information on the Elixir, subscribe to our newsletter.



Thank you for DMK Press publishing "Introduction to Elixir" and leave promo code for 25% specifically for habrovky Elixir_Habr (valid until 14th).


I hope my review is useful to you. All a good day and plenty of useful books!

PS Friends, subscribe to our group and channel in the Telegram. As soon as you typed a total of 600 participants, we will raffle the book Metaprogramming Elixir.
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

Why I left Google Zurich

2000 3000 icons ready — become a sponsor! (the table of orders)

New web-interface for statistics and listen to the calls for IP PBX Asterisk