3. Things I know
• We are interested in Elixir.
• We need to learn.
• Learning together is fun.
• Elixir is fun.
• Our meet-ups well be practical: we’ll write code.
4. Things I don’t know
• How often we get together.
• Your background and your level.
• Let’s get acquainted!
5. Thus
• Let’s experiment!
• Everyone is welcome to take initiative and organize
the next session, possibly in a different way!
8. • In use for ~20 years.
• Designed at Ericsson
• Fault tolerant, scalable, distributed, responsive
systems.
• Erlang the language is a functional and concurrent
programming language with a dynamic type system
• Erlang the language is rather conservative
9. What makes Erlang unique
• Lightweight isolated process as the building block
• Processes communicate via asynchronous
messages
• Error handling approach: LET IT CRASH approach
• OTP
11. Elixir
• Modern
• Functional
• Concurrent
• Transparent integration with the Erlang world
• Protocol-based polymorphism
• Macros
• Focus on tooling
17. Consequences of
Immutability
• There is no question of equality and identity, like in
Java .
Date a = new Date(123);
Date b = new Date(123);
Date c = a;
System.out.println(a == b); //=> false
System.out.println(a.equals(b)); //=> true
System.out.println(a == c); //=> true
18. a = {2014, 9, 11}
b = {2014, 9, 11}
c = a
IO.inspect a == b #=> true
IO.inspect a == c #=> true
IO.inspect b == c #=> true
Equality and Identity the
Functional Way
20. Functions transform data
defmodule Example do
def word_signature word do
without_spaces = String.strip(word)
downcased = String.downcase(without_spaces)
letters = String.split(downcased, "", trim: true)
sorted = Enum.sort(letters)
Enum.join(sorted)
end
end
IO.inspect Example. word_signature(” Higher ”)
21. Functions transform data
defmodule Example do
def word_signature word do
Enum.join(Enum.sort(String.split(
String.downcase(
String.strip(word)), "", trim: true)))
end
end
IO.inspect Example. word_signature(” Higher ”)
22. OR:
defmodule Example do
def word_signature word do
word |> String.strip
|> String.downcase
|> String.split("", trim: true)
|> Enum.sort
|> Enum.join
end
end
IO.inspect Example. word_signature(” Higher ”)
23. FP & OO
• Functional programming does not contradict Object
Orientedness if objects are immutable. Example:
Scala.
• But neither Erlang nor Elixir has classes
• You separate code and data
24. Abstracting with modules
peter = Person.new(“Peter”,”Peterson”, 20)
IO.inspect Person.can_drink_alcohol?(peter)
#=> false
peter = Person.birthday(peter)
IO.inspect Person.can_drink_alcohol?(peter)
#=> true
25. Abstracting with modules
defmodule Person do
defstruct firstname: nil, lastname: nil, age: 0
@legal_drinking_age 21
def new(fname, lname, age) do
%Person{firstname: "Peter",
lastname: "Peterson", age: 20}
end
26. Abstracting with modules
def can_drink_alcohol?(person) do
person.age >= @legal_drinking_age
end
def birthday(person) do
%{person | age: person.age + 1}
end
end
i hope this is the first and the last presentation
Xavier and Yuri
responsible anarchy :)
but practical and about Elixir
we are not Yodas
OTP framework (Open Telecom Platform) inseparable from Erlang. And Elixir ;-)
BEAM
lfe.io joxa.org
Поэтому в Erlang за счет того, что очень проработан весь pipeline компилятора, в нем есть несколько уровней языковых. Один из самых низких уровней, который все слышали – это Erlang core. Erlang core – это такой ерланговый DSL для представления структуры программы ерланговской в виде элементарных синтаксических конструкций. Но в Erlang core нет рекордов потому, что Erlang core – это уже скомпилированная программа. А есть на уровень выше, допустим, Erlang AST. В Erlang AST есть упоминание о Erlang record, т.е. там вы можете делать макросы, инклюды, которые у вас есть, директивы компилятора. Они все тоже в Erlang AST включаются. И там уже, как бы, сразу вы даете, вот моя программа, вот допустим, там есть какой-то свитч или pattern matching.
Если вы даете Erlang-у Erlang AST, он его сам скомпилирует до Erlang core и прооптимизирует. И, вот, Elixir построен точно таким образом. Elixir не генерирует байт-код, он генерирует Erlang AST из эликсировской программы и дает на компиляцию компилятору Erlang-а. Компилятор Erlang уже производит сам все необходимые оптимизации. И вот такой путь позволяет очень быстро делать прототипы языков для языковой среды Erlang-а. Если вы пишите, вам достаточно просто написать какой-то лексер и парсер, и вы сразу сможете сгенерировать AST. Т.е., по сути, это будет просто какой-то препроцессор DSL из вашего языка в Erlang AST. А дальше все оптимизации, pattern matching компиляции, все эти штуки, рекорды, все это сделает за вас компилятор Erlang-а. Это намного меньше сил нужно тратить разработчику компиляторов языков для платформы Erlang, допустим, люди тратят при написании компилятора для .Net и для Java. И в этом вот и крутость, это очень круто! И я поощряю развитие любых синтаксисов под Erlang, возможно кто-то возьмет и напишет сиподобную лапшу-синтаксис для Erlang, почему бы нет?
open sourced later
prolog roots both in syntax and semantics
1st version implemented in prolog
designed by engineers who like to sleep at night
boxes which work reliably for years
0 syntax sugar
mention maps
3
Not the CPU process.
Processes are very lightweight (a newly spawned process takes a bit more than 300 bytes!)
Each process is isolated from other processes: its own GC
There can be thousands or even millions of processes in one Erlang VM (node).
whatsapp claimed 3 million open sockets on 1 freebsd server
2
its own mailbox
Sometimes it makes more sense to think of Erlang processes as objects in OO languages, and not as of OS processes, or threads.
Processed are managed by schedulers. In BEAM there is one scheduler per each CPU core.
Two processes can be linked together, termination (normal or abnormal) of one process emits an exit signal, and a linked process can process this signal and do something about it, or get terminated.
It is important to note that event though these primitives enable miracles and it is important to know and understand them, you seldom use them directly. There are higher-level abstractions which implement common patterns of concurrent programming. These abstractions are a set of libraries called OTP: Open Telecom Platform.
modern language for the Erlang platform.
transparent integration with the Erlang world
stays close to its roots,. Thus, inherits all the merits of the Erlang VM and the OTP framework.
tooling still in progress
ok, mention Rails
In my humble opinion, unlike Erlang the language, Elixir can be a general purpose language, allowing you to write concurrent code, which would use all your 4/8/16…CPU cores (or servers).
IMHO!
laziness …
a higher-order function is a function that does at least one of the following: (1) takes one or more functions as an input or (2) outputs a function
There is only equality in functional languages and you don’t care about where that thing in stored in memory.
no void
Pure functions are very testing-friendly. Pure functions/methods make much sense in any mainstream language
Surely there are still side-effects: I/O. In Erlang there is ETS and process name registration facilities which are an equivalent of global variables.