The document discusses concepts in Elixir including pattern matching, processes, global variables, and supervision. It provides examples of spawning processes, sending messages between processes, linking processes, and using the Agent module to implement a global stack data structure. It also shows how to create a supervisor module to restart the stack process if it crashes, providing fault tolerance.
11. defmodule Teste do
def say(name) do
IO.puts("Hello #{name}")
end
end
Teste.say("Fabio")
defmodule Teste do
@spec say(String.t)
def say(name) when is_string(name) do
IO.puts "Hello " <> name
end
end
Teste.say "Fabio"
13. -module(teste).
-export([qsort/1]).
qsort([]) -> [];
qsort([Pivot|T]) ->
qsort([X||X<-T,X =< Pivot]) ++
[Pivot] ++
qsort([X||X<-T,X > Pivot]).
defmodule Teste do
def qsort([]), do: []
def qsort([pivot|t]) do
qsort(for x <- t, x < pivot, do: x) ++
[pivot] ++
qsort(for x <- t, x >= pivot, do: x)
end
end
14. defmodule Teste do
def factorial(n) do
if n == 0 do
1
else
n * factorial(n - 1)
end
end
end
Teste.factorial(10)
# => 3628800
defmodule Teste do
def factorial(0), do: 1
def factorial(n) do
n * factorial(n - 1)
end
end
Teste.factorial(10)
# => 3628800
24. function = fn -> IO.puts("Hello from function") end
function.()
# => Hello from function
pid = spawn(function)
# => Hello from function
Process.alive?(pid)
# => false
Process.alive?(self)
# => true
25. pid = spawn(fn ->
receive do
{:say, from} ->
send(from, "say what?")
_ ->
Process.exit(self, :normal)
end
end)
Process.alive?(pid)
# => true
send(pid, {:say, self})
receive do
message ->
IO.puts("Recebido: " <> message)
end
# => Recebido: say what?
send(pid, "blabla")
Process.alive?(pid)
# => false
33. defmodule Stack do
def start_link do
Agent.start_link(fn -> [] end,
name: __MODULE__)
end
def pop do
Agent.get_and_update(__MODULE__,
fn(state) ->
[head|tail] = state
{head, tail}
end)
end
def push(new_value) do
Agent.update(__MODULE__,
fn(state) ->
[new_value|state]
end)
end
end
35. defmodule Stack.Supervisor do
use Supervisor
def start_link do
Supervisor.start_link(__MODULE__, :ok)
end
def init(:ok) do
children = [
worker(Stack, [])
]
supervise(children, strategy: :one_for_one)
end
end