
It happened suddenly, but brought a sea of joy. Finally, the book publisher drew attention to the interest of developers Elixir and released the
first book on this language in Russian . The choice of publications for translation is expected - this is material for people who want to get acquainted with the language or have already begun to meet and are ready to learn more about the possibilities.
Elixir is a dynamic, functional programming language designed to create scalable and easily supported applications. Based on Erlang VM, effective for low-latency distributed, fault-tolerant systems, while being successfully used in web development and embedded software.
"Introduction to Elixir" is the standard representative of the literature on programming languages. The story is conducted sequentially, from the basics of syntax to advanced modules and techniques. The examples are synthetic, but at the same time they illustrate the text in such a way that it immediately becomes clear what is being said. Given that the language is expressive, and the set of tools inherited from Erlang is impressive, you should not be bored.
')
Further I will consider each of chapters in more detail.
Chapter 1. Sit back
Everything is standard here. Preparing to work with the language, explaining the basics of the basics and a short
workshop on working with the interactive shell .
Chapter 2. Functions and Modules
After 20 minutes of work with the book, we are already introduced to the main charm and beauty of the language - function. It would seem that nothing unusual - just one of the elements of the language. But in reality, the function in the Elixir is its foundation.
And here the first unusual possibilities of the language are revealed. For example, combining functions via a pipe when such a construction
Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)
turns into an elegant look
[1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)
Or how do you like this feature? Adding comments to functions you can immediately receive full documentation, built-in language tools.
Chapter 3. Atoms, Tuples, and Pattern Matching
Experience with the book depends on what languages you are already familiar with. If you have not previously encountered functional languages or are not familiar with Ruby's syntax, revelations will begin here.
First, the elixir uses the atom data type. It seems to be nothing special, the elements of this type have the same value as the name.
iex(1)> :test :test
But such a simple idea essentially (using other language mechanisms) influences the programming style on the Elixir.
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, the same function is not redefined here three times. In fact, these are 3 different functions, each of which can be selected through comparison with the sample of the first argument-atom.
This is the main technique of the language with which you can work wonders. And the book tells how to do it. Whether using protection conditions or more complex than ordinary atoms, comparisons with the sample.
Chapter 4. Logic and Recursion
Programs in functional languages are usually written more using recursion than through standard cycles. To learn how to write recursion correctly, which the compiler can optimize, see this chapter. Due to the pattern matching, which is used both in security conditions and in logical expressions, the recursion is very elegant and unusual.
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
Chapter 5. Human interaction
One of the main technical differences of the Elixir from Erlang is the complete processing of the string operation mechanism. Now it is not just a list of characters, but a full-fledged binary data type that Unicode can support. And it is thanks to the lines that we can interact with the user.
Chapter 6. Lists
I hope that I manage to awaken your interest in the language. In addition to interesting syntactic features and cool ideas at the core, everything works amazingly fast. Not for nothing, the Elixir is compared in speed with Go and Rast, and in speed with Ruby.
The elixir has excellent support for lists, long sequences of meanings. They help evaluate the benefits of recursion and allow you to perform a large amount of work with minimal effort. Although this is the standard data type for functional languages, there is something to talk about here.
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 a functional programming with a human face.
Chapter 7. Name / Value Pairs
I am sometimes asked. Since there are no objects in the Elixir, then how do we work with structured data? Tuples and lists are good, but they do not allow you to get a value by name. An elixir, though young, but already mature (
even production is rare ) language. Therefore, the developers have provided mechanisms for solving this problem. In the Elixir there are data types in which you can get the value by key. And in this chapter they are considered - from the dictionary to the structure.
Chapter 8. Higher Order Functions and List Generators
Higher-order functions, or functions that take other functions in arguments, help the Elixir to manifest in all its brilliance. It cannot be said that in other languages it is impossible to implement similar functions, it is possible in almost any languages, but in the Elixir, functions of a higher order are interpreted as a natural part of the language, and not as an artificial and alien formation.
Not the most interesting chapter, but to learn about these opportunities is not superfluous.
Chapter 9. Processes
If you have a good programming experience, then up to now you might be bored. I hasten to please you, the most interesting thing about the killer-features of Elixir begins right now!
When describing an Elixir, some processes are usually mentioned as advantages. They say that they allow to achieve distribution, increase the speed of the program, are used when scaling and hot-swapping code, but it is not at all clear what they are and how they look within the language itself.
In fact, processes are another organizational unit of the program, along with functions and modules, which is an independent component capable of receiving and sending messages. A running program is a collection of processes.
The conversation begins in this chapter with an interactive shell, which is also a process. Processes are discussed in great detail and in detail; additional tools for working with them are also considered.
Chapter 10. Exceptions, Errors, and Debugging
With
debugging in the Elixir, not everything is smooth, as there are no full-fledged native tools. The most popular are
Pry
(which came from Ruby) and
:dbg
(from Erlang). In fact, they are quite comfortable to use, and the book gives a good analysis of the second one.
Chapter 11. Static Analysis, Type Specifications, and Testing
There are three main classes of errors in programming: syntax errors, run-time errors and semantic errors. The Elixir compiler detects and reports syntax errors. Logical errors remain when you demand one from Elixir, meaning the other. Logging and tracing can help in finding such errors, but it is still better to try to prevent them from occurring right from the start. And this will help you static analysis, type specifications and unit testing. All this is covered in this chapter.
Elixir has very nontrivial capabilities in these areas. For example, tests embedded in the documentation:
defmodule Drop do @doc """ ( ̆ ̆) 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 sure that the documentation will always be up to date!
Chapter 12. Storing Structured Data
No matter how we would like to have pure functions, in practice it is impossible, because the data must be stored somewhere. For this, Erlang has a bunch of built-in tools, which fortunately can be used from the Elixir. This chapter deals with ETS and Mnesia.
Just imagine that you no longer need Radishes, as an external addiction. After all, its "substitute" is built right into the language and is supported out of the box.
Chapter 13. Basic OTP
Everyone coming to the world of Erlang and Elixir, hears about a certain OTP, which is discussed by more experienced colleagues. On the subcortex, it is postponed that this is some kind of very cool thing, incredibly useful and just masthy in everyday development. But what is it is absolutely not clear.
It turns out that OTP is a framework for writing parallelized and highly reliable applications. It uses all the Erlang virtual machine chips and allows programmers to think only about business logic, and not about implementation details.
The most popular modules are Supervisor and GenServer. They look like this:
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
Learn more about them
here and
here . Or in the current chapter of the book.
And the Elixir offers the thing that all erlangists dream about - the Mix utility.
Her review is also in the book.
Chapter 14. Extending the Elixir Language with Macros
The next feature that distinguishes Elixir from Erlang is advanced metaprogramming. It is implemented through the creation of macros. Externally, macros are very similar to functions, differing only in the fact that they start with the
defmacro
instruction instead of the
def
. However, macros act quite differently than functions. Because of this, you can create a cool DSL, not tempting rushny.
Chapter 15. Phoenix
Well, the book ends with such an important topic as the Phoenix. This is a web framework that I want to compare with Rails. Phoenix inherited rail philosophy and some approaches, although now it is gradually moving aside. But it should be noted that the Phoenix is the same engine for the Elixir, as well as at one time Rails for Ruby.
The introductory course on Phoenix can be found in the book or
in this series of articles , which I translate for Habr.
findings
The book is extremely suitable. I have been involved in the Wunsh project for several months, where we introduce Russian-speaking readers to the beautiful Elixir. And it was still interesting for me to read the book, I managed to get some nuances when working with familiar parts of the language and learn about other opportunities that I hadn’t encountered before.
The text contains links to interesting articles on Elixir, which we translate as part of Wunsch. If you want to receive useful information on the Elixir weekly, subscribe to our newsletter .
What is important to note, and for what I was most worried, is the translation. And fortunately, it turned out pretty successful. Nadmusz is practically absent, and translations of the terms, although I would like to leave a little more anglicified, do not cut off the rumor. Such a tribute to academicity is quite appropriate.
I thank DMK Press for the publication “Introduction to Elixir” and leave the promotional code for 25% specifically for habrovchan Elixir_Habr (valid until the 14th).
I hope my review is useful to you. Have a good day and more useful books!
PS Friends, subscribe to our group and channel in the Telegram. As soon as we have 600 participants in total, we will play the book Metaprogramming Elixir.