Elixir este un limbaj functional dinamic construit pentru aplicatii scalabile si tolerante la erori pe masina virtuala Erlang (BEAM).
🔗 Conex: Ghid rapid Metaprogramare in Elixir · Ghid rapid Absinthe GraphQL · Ghid rapid Phoenix Framework
Primii pași (Getting Started)
# hello.exs
defmodule Greeter do
def greet(name) do
message = "Hello, " <> name <> "!"
IO.puts(message)
end
end
Greeter.greet("world")
Rulare prin CLI-ul Elixir:
elixir hello.exs
# => Hello, world!
Variabile și imutabilitate (Variables & Immutability)
age = 23
age = 24 # Reasociere (nu modifica valoarea initiala)
Hărți (Maps)
user = %{
name: "John",
city: "Melbourne"
}
IO.puts("Hello, " <> user.name)
Liste (Lists)
users = ["Tom", "Dick", "Harry"]
Enum.each(users, fn user ->
IO.puts("Hello " <> user)
end)
Operatorul Pipe (Pipe Operator |>)
Transmite rezultatul expresiei din stanga ca prim argument functiei din dreapta:
source
|> transform(:hello)
|> print()
# Echivalent cu:
print(transform(source, :hello))
Potrivire de tipare (Pattern Matching)
Operatorul = actioneaza ca un operator de potrivire structurala de tipare:
user = %{name: "Tom", age: 23}
%{name: username} = user
# username is bound to "Tom"
# Operatorul pin (^) compara valoarea existenta fara reasociere
x = 1
^x = 1 # Succes
# ^x = 2 # Eroare MatchError
Potrivire de tipare în antetele funcțiilor
defmodule UserGreeter do
def greet(%{name: username}) do
IO.puts("Hello, " <> username)
end
end
Controlul fluxului (Control Flow)
if & unless
if status == :ok do
"Ready"
else
"Pending"
end
case
case {1, 2, 3} do
{4, 5, 6} -> "No match"
{1, x, 3} -> "Matches and binds x to 2"
_ -> "Wildcard matches any value"
end
cond
Evalueaza conditiile secvential pana la prima expresie adevarata:
cond do
1 + 1 == 3 -> "Never matches"
2 * 5 == 12 -> "Neither"
true -> "Matches (acts as else)"
end
with
Conecteaza potrivirile in mod sigur si se opreste la prima eroare:
with {:ok, {int, _}} <- Integer.parse("123abc"),
{:ok, datetime, _offset} <- DateTime.from_iso8601("2026-10-25T12:00:00Z") do
DateTime.add(datetime, int, :second)
else
:error -> "Invalid integer format"
{:error, :invalid_format} -> "Invalid ISO datetime"
_ -> "Unhandled error"
end
Tipuri și operatori (Types & Operators)
is_atom/1 is_boolean/1 is_binary/1
is_integer/1 is_float/1 is_number/1
is_list/1 is_map/1 is_tuple/1
is_nil/1 is_function/1 is_pid/1
Colecții și structuri de date (Collections & Data Structures)
Maps
m = %{name: "Alice", age: 30}
# Sintaxa pentru actualizarea unei chei existente
m = %{m | age: 31}
# Functii ale modulului Map
Map.get(m, :name) # "Alice"
Map.put(m, :city, "Tokyo") # Adds :city
Map.delete(m, :age) # Removes :age
Map.merge(m, %{active: true}) # Merges maps
Lists & Enums
list = [1, 2, 3, 4]
# Adaugare la inceput O(1) si la sfarsit O(N)
[0 | list] # [0, 1, 2, 3, 4]
list ++ [5] # [1, 2, 3, 4, 5]
# Operatii cu Enum
Enum.map(list, &(&1 * 2)) # [2, 4, 6, 8]
Enum.filter(list, fn x -> rem(x, 2) == 0 end) # [2, 4]
Enum.reduce(list, 0, &+/2) # 10
Funcții (Functions)
# Functie anonima
add = fn a, b -> a + b end
add.(2, 3) # 5
# Sintaxa de capturare
square = &(&1 * &1)
square.(5) # 25
# Captura referinta la functie
fun = &String.upcase/1
fun.("hello") # "HELLO"
Structuri și protocoale (Structs & Protocols)
defmodule User do
defstruct name: "", age: nil
end
user = %User{name: "Alice", age: 30}
user.name # "Alice"
defprotocol Blank do
@doc "Returns true if data is empty"
def blank?(data)
end
defimpl Blank, for: List do
def blank?([]), do: true
def blank?(_), do: false
end
Blank.blank?([]) # true
Generator de liste (for)
for n <- 1..5, do: n * 2
# => [2, 4, 6, 8, 10]
for n <- 1..10, rem(n, 2) == 0, do: n
# => [2, 4, 6, 8, 10]
for {k, v} <- %{a: 1, b: 2}, into: %{}, do: {k, v * 10}
# => %{a: 10, b: 20}
Comportamente și specificații de tip (Behaviours & Type Specs)
defmodule Parser do
@callback parse(String.t()) :: {:ok, any()} | {:error, String.t()}
@callback extensions() :: [String.t()]
end
defmodule JSONParser do
@behaviour Parser
@impl Parser
def parse(str), do: {:ok, str}
@impl Parser
def extensions, do: [".json"]
end