Erlang and Elixir

29
Erlang & Elixir workshop #1 :: erlang 101 Created by / Krzysztof Marciniak @hun7err

Transcript of Erlang and Elixir

Page 1: Erlang and Elixir

Erlang & Elixirworkshop #1 :: erlang 101

Created by / Krzysztof Marciniak @hun7err

Page 2: Erlang and Elixir

ErlangYou can the introduction.skip

Page 3: Erlang and Elixir

Source:

What is Erlang?Erlang is a programming language used to buildmassively scalable soft real-time systems with

requirements on high availability. Some of its usesare in telecoms, banking, e-commerce, computer

telephony and instant messaging. Erlang's runtimesystem has built-in support for concurrency,

distribution and fault tolerance.

Erlang homepage

Page 4: Erlang and Elixir

Source:

What is Erlang?Erlang's syntax is very similar to Prolog's, but thesemantics are very different. An early version of

Erlang was written using Prolog, but today's Erlangcan no longer meaningfully be said to be "based

on Prolog."

StackOverflow

Page 5: Erlang and Elixir

Why Erlang?it's functional!it's multi-threaded!high-availabilityeasy distributioncode hot-swap

Page 6: Erlang and Elixir

Components of Erlangvirtual machine - the new BEAM (Bogdan/Björn's Erlang AbstractMachine)OTP - Open Telecom Platform, a framework/libraryerl - Erlang interactive consolerebar* - an Erlang build tool [ ]GitHub

* technically it's not an official component, but it is very useful

Page 7: Erlang and Elixir

The absolute basics-module(ex1).-export([add/2]).

add(X, Y) -> X + Y.

1> c(ex1).{ok,ex1}2> ex1:add(2, 3).53>

$ erl -man [module_name]

io, lists, etc.

Page 8: Erlang and Elixir

Recursive functions-module(fac).-export([fac/1]).

fac(1) -> 1; % function clausefac(N) -> N * fac(N - 1).

Page 9: Erlang and Elixir

Higher-order functions1> X = fun(X) -> X * 4 end.2> X(4).163>

Page 10: Erlang and Elixir

Lists[Head | Tail] = [1,2,3,4] % list decomposition[First, Second | Tail] = [1,2,3,4] % ( ͡° ͜ʖ ͡°)

lists:reverse([1,2,3,4])lists:append([1,2], [3,4])lists:append([[1,2],[3,4],[5,6]])lists:filter(fun(X) -> X rem 2 == 0 end, [1,2,3,4,5,6]) % only even numbers

lists:foldl(fun(X, Sum) -> X + Sum end, 0, [1,2,3,4,5]) % sum% ̂--- fold left, might sound familiar% erl -man lists

Page 11: Erlang and Elixir

Stop! Hammer time.(excercises)

1. Create a list_reverse function2. Write a custom map function (list_map)

Page 12: Erlang and Elixir

Lightweight threads-module(simplethreads).-export([start/1]).

hello(Text) -> io:format("Hello, ~p!~n", [Text]).

start() -> spawn(simplethreads, hello, ["World"]).

That should return PID of the spawned process, i.e. <0.59.0>

Page 13: Erlang and Elixir

Threads + Recursion =Awesomeness

-module(threads).-export([start/0, say/2]).

say(_, 0) -> done;say(Text, Times) -> io:format("~p~n", [Text]), say(Text, Times-1).

start() -> spawn(threads, say, ["hello", 5]), spawn(threads, say, ["bye", 5]).

Page 14: Erlang and Elixir

Interprocess communication(1/2)

-module(simplethreads).-export([start/0, say/0]).

say() -> receive Text -> io:format("Hello, ~p!~n", [Text]) end.

start() -> Pid = spawn(simplethreads, say, []), timer:sleep(200), Pid ! "World", ok.

Page 15: Erlang and Elixir

Interprocess communication(2/2.1)

-module(pingpong).-export([start/0]).

ping(0, PongPID) -> PongPID ! finished, io:format("ping finished~n", []);ping(N, PongPID) -> PongPID ! {ping, self()}, receive pong -> io:format("pong~n", []) end, ping(N-1, PongPID).

% continued on the next slide

Page 16: Erlang and Elixir

Interprocess communication(2/2.2)

pong() -> receive finished -> io:format("pong finished~n", []); {ping, PingPID} -> io:format("ping~n", []), PingPID ! pong, pong() end.

start() -> PongPID = spawn(pingpong, pong, []), spawn(pingpong, ping, [5, PongPID]).

Page 17: Erlang and Elixir

Interprocess communicationEshell V7.1 (abort with ̂G)1> c(pingpong).{ok,pingpong}2> pingpong:start().ping<0.42.0>pongpingpongpingpongpingpongpingpongping finishedpong finished3>

Page 18: Erlang and Elixir

OTP - Open Telecom PlatformOTP stands for Open Telecom Platform, although

it's not that much about telecom anymore (it'smore about software that has the property of

telecom applications, but yeah.) If half of Erlang'sgreatness comes from its concurrency and

distribution and the other half comes from itserror handling capabilities, then the OTP

framework is the third half of it.

Page 19: Erlang and Elixir

OTP example-module(server).-behaviour(myserver).-export([ % The behaviour callbacks init/1, % - initializes our process handle_call/3, % - handles synchronous calls (with response) handle_cast/2, % - handles asynchronous calls (no response) handle_info/2, % - handles out of band messages (sent with !) terminate/2, % - is called on shut-down code_change/3]). % - called to handle code changes

Page 20: Erlang and Elixir

ElixirThe new youth of Erlang

Page 21: Erlang and Elixir

What is Elixir?Elixir is a dynamic, functional language designed

for building scalable and maintainableapplications. Elixir leverages the Erlang VM, known

for running low-latency, distributed and fault-tolerant systems, while also being successfullyused in web development and the embedded

software domain.

Page 22: Erlang and Elixir

The basics:hello # an atom"utf string ąę" # in erlang that would not be so easy hello = "a thing" # no longer capitalized, yay!hello = :hello # notice how we can overwrite the valueIO.puts("hello\nworld")length([1,2,3]) # I'll speak of lists in a secondlength [1,2,3] # notice how we can skip brackets

Page 23: Erlang and Elixir

Listsiex> a_list = [1,2,3,4,5][1,2,3,4,5]iex> a_list = a_list ++ [6][1,2,3,4,5,6]iex> a_list -- [1,3,5][2,4,6]iex> [head|tail] = [1,2,3,4] # also hd/1, tl/1[1,2,3,4]iex> head1iex> tail[2,3,4]iex> [104, 101, 108, 108, 111]"hello"

Page 24: Erlang and Elixir

Tuplesiex> tuple = {:ok, "hello"}{:ok, "hello"}iex> put_elem(tuple, 1, "world"){:ok, "world"}iex> tuple # Elixir types are immutable{:ok, "hello"}iex> tuple_size tuple2

Page 25: Erlang and Elixir

Modules and functionsdefmodule Calculator do def add(x, y) do x + y endend

defmodule Lists do def reverse([head|tail], acc) do reverse(tail, [head|acc]) end # function clauses do not have to be distinguished def reverse([], acc) do acc endend

Page 26: Erlang and Elixir

If macro, keywords, maps anddicts

iex> if false, do: :this, else: :that:thatiex> if(false, [do: :this, else: :that]):thatiex> if(false, [{:do, :this}, {:else, :that}]):thatiex> map = %{:a => 1, :b => 2}%{a: 1, b: 2}iex> list = [a: 1, b: 3][a: 1, b: 3]iex> Dict.put list, :a, 4[a: 4, b: 3]iex> Dict.put map, :a, 4 %{a: 4, b: 2}

Page 27: Erlang and Elixir

Phoenix frameworkPhoenix is a web development framework written

in Elixir which implements the server-side MVCpattern. Many of its components and concepts will

seem familiar to those of us with experience inother web frameworks like Ruby on Rails or

Python's Django.

Page 28: Erlang and Elixir

Getting started with Phoenix$ mix local.hex$ mix archive.install https://github.com/phoenixframework/phoenix/releases/download/v1.1.0/phoenix_new-1.1.0.ez$ mix phoenix.new hello$ mix ecto.create$ mix phoenix.server

Page 29: Erlang and Elixir

BibliographyThe official "Getting started" guide -

Learn You Some Erlang - Erlang Doc on distributed systems - OTP for beginners - Elixir Lang homepage - Phoenix Framework homepage -

http://www.erlang.org/download/getting_started-5.4.pdfhttp://learnyousomeerlang.com/

linklink

http://elixir-lang.org/

http://www.phoenixframework.org/