Fundamentos
Hola Mundo y Módulos
Cada archivo Erlang es un módulo declarado con -module(name). Las funciones exportadas se listan con -export([name/arity]). La aridad (número de argumentos) es parte de la identidad de la función — greet/0 y greet/1 son funciones distintas. Compile desde la shell con c(Module).
% hello.erl
-module(hello).
-export([greet/1, greet/0]).
greet() ->
greet("World").
greet(Name) ->
io:format("Hello, ~s!~n", [Name]).
% Compile & run in the shell:
% c(hello).
% hello:greet("Alice"). %=> Hello, Alice!Variables y Átomos
Las variables empiezan con mayúscula (o _) y son de asignación única — una vez ligadas no cambian. Re-matching una variable ligada es una aserción: X = X+1 lanza un error badmatch. Los átomos son constantes con nombre que empiezan con minúscula; se comparan por identidad.
Name = "Alice". % variables start with uppercase
Age = 30. % bound once — single assignment!
% Age = 31. % ** exception error: no match of RHS
% Atoms start with lowercase (or are quoted)
ok. % the ok atom (common return value)
error. % another atom
'This is an atom'. % quoted atom with spaces
true, false, undefined % built-in atoms
% Pattern matching binds and asserts
{ok, Result} = {ok, 42}. % Result = 42
{error, _} = {error, badarg}. % _ matches and discardsTuplas y Registros
Las tuplas son contenedores de tamaño fijo escritos {a,b,c}. Los registros son tuplas con campos nombrados, declarados con -record. Actualizar un campo crea un nuevo registro (datos inmutables). El primer elemento es convencionalmente un átomo etiqueta.
% Tuples (fixed-size, positional)
Point = {point, 3, 4}.
{point, X, Y} = Point. % X=3, Y=4
element(2, Point). %=> point
% Records (syntactic sugar over tuples)
-record(person, {name, age, city = "Unknown"}).
P = #person{name = "Alice", age = 30}.
P#person.name. %=> "Alice"
P2 = P#person{age = 31}. % update field
{person, Name, Age, _} = P. % underlying tupleListas y Comprensiones
Las listas son listas enlazadas construidas con [Head|Tail]. ++ concatena (O(n) a la izquierda), -- elimina elementos. Las comprensiones [Expr || Calificador1, ...] soportan generadores (X <- List) y filtros (expresiones booleanas).
[1,2,3] ++ [4,5]. %=> [1,2,3,4,5] (append)
[1,2,3] -- [2]. %=> [1,3] (subtract)
hd([1,2,3]). %=> 1 (head)
tl([1,2,3]). %=> [2,3] (tail)
% Pattern matching on lists
[Head | Tail] = [1,2,3]. % Head=1, Tail=[2,3]
[A,B|Rest] = [1,2,3,4]. % A=1, B=2, Rest=[3,4]
% List comprehensions
[ X*2 || X <- [1,2,3,4] ]. %=> [2,4,6,8]
[ X || X <- [1..10], X rem 2 =:= 0 ]. % evens: [2,4,6,8,10]
[ {A,B} || A <- [1,2], B <- [a,b] ]. % cartesian productFunciones y Pattern Matching
Las funciones se definen como múltiples cláusulas separadas por ;. Las cláusulas se prueban en orden; la primera cuyo patrón Y guarda tienen éxito se usa. Las tuplas etiquetadas {ok, Val} / {error, Reason} señalan éxito/fracaso sin excepciones.
-module(math_tools).
-export([factorial/1, fib/1, classify/1]).
% Multiple clauses selected by pattern matching
factorial(0) -> 1;
factorial(N) when N > 0 -> N * factorial(N - 1).
% Fibonacci with guards
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N > 1 -> fib(N-1) + fib(N-2).
% Tagged returns (common Erlang idiom)
classify(X) when X < 0 -> {negative, X};
classify(0) -> zero;
classify(X) when X > 0 -> {positive, X}.Mapas
Los mapas (desde R17) son diccionarios clave-valor. Use => para establecer/insertar y := para actualizar (la clave debe existir). En pattern matching solo se permite :=. maps:get/2 lanza badarg en claves ausentes; use maps:get/3 para un valor por defecto.
% Create
M = #{ name => "Alice", age => 30, role => admin }.
% Lookup
maps:get(name, M). %=> "Alice"
maps:get(city, M, "Unknown"). % default if missing
{ok, V} = maps:find(age, M). %=> {ok, 30}
% Update / add (immutable — returns new map)
M2 = M#{ age => 31, city => "Paris" }.
% Pattern match on maps
#{ name := N } = M. % N = "Alice" (:= for matching, => for setting)
#{ age := A, role := R } = M.Pattern Matching y Guardas
Pattern Matching en Cabezas de Función
Erlang selecciona una cláusula de función haciendo pattern matching de los argumentos de arriba a abajo. Los patrones pueden ligar variables, afirmar igualdad con literales e ignorar campos con _. El mismo mecanismo se usa en receive, case y =.
% Select clause by structure of argument
handle({ping, From}) -> From ! pong;
handle({echo, Msg}) -> Msg;
handle({add, A, B}) -> A + B;
handle(stop) -> bye.
% Tuple destructuring
-record(rect, {w, h}).
area(#rect{w=W, h=H}) -> W * H.
% List patterns with literal values
greet_first([H|_]) -> io:format("Hi ~p~n", [H]);
greet_first([]) -> ok.Expresiones case
case evalúa una expresión y la compara con una secuencia de patrones. Cada cláusula puede tener una guarda. Es la herramienta de control estándar cuando la ramificación depende de un valor calculado. Incluya siempre una cláusula _ general salvo que quiera un crash.
classify_file(Size) ->
case Size of
0 -> empty;
N when N < 1024 -> small;
N when N < 1048576 -> medium;
_ -> large
end.
% Matching on tagged tuples
Result = case file:read_file("a.txt") of
{ok, Bin} -> {ok, binary_to_list(Bin)};
{error, enoent} -> {error, missing};
{error, Reason} -> {error, Reason}
end.Guardas
Las guardas restringen cuándo una cláusula coincide. Se limitan a un conjunto conocido de funciones integradas para que siempre terminen y no tengan efectos secundarios. Coma = AND, punto y coma = OR. Prefiera pattern matching sobre guardas cuando sea posible.
% Guards go after 'when' and may use built-in guard tests (BIFs)
max(A, B) when A >= B -> A;
max(_, B) -> B.
% Multiple guard tests: ',' = AND, ';' = OR
classify(N) when N > 0, N < 100 -> in_range;
classify(N) when N =< 0; N >= 100 -> out_of_range.
% Allowed guard BIFs include comparison, arithmetic, type tests:
% is_integer/1, is_atom/1, is_list/1, is_map/1,
% length/1, map_size/1, abs/1, element/2, hd/1, tl/1
% (No user functions — guards must be side-effect free and terminate!)Sintaxis de Bits y Binarios
La sintaxis de bits << Seg1, Seg2, ... >> empaqueta/desempaqueta binarios por campos de bits. Cada segmento es Value:Size/TypeSpecifier. Esto hace a Erlang excepcionalmente bueno analizando protocolos de red y formatos de archivo.
% Pack a 16-bit length + 8-bit type + payload
Bin = << Length:16, Type:8, Payload/binary >>.
% Unpack with the same pattern
<< L:16, T:8, Rest/binary >> = Bin.
% Bit fields & endianness
<< N:32/big-unsigned-integer >> = <<0,0,1,1>>. % N = 261
<< N:32/little-signed-integer >> = <<1,0,0,0>>. % N = 1
% IPv4 header parsing example
<< Version:4, IHL:4, _TOS:8, TotalLen:16,
_/binary >> = Packet.Programación Concurrente
spawn — Iniciar un Proceso
spawn(M,F,A) crea un nuevo proceso BEAM — un hilo verde ligero con su propio heap y buzón. Los procesos no comparten memoria y se comunican solo por paso de mensajes. BEAM puede ejecutar decenas de millones de procesos; cada uno ocupa ~2-3 KB.
% spawn/3 starts a new lightweight process
Pid = spawn(Module, Function, ArgsList).
Pid = spawn(fun() -> timer:sleep(1000), io:format("done~n") end).
% Every process has a PID; processes share NO memory
% (BEAM processes are NOT OS threads — millions are possible)
% self() returns the current process's PID
io:format("I am ~p~n", [self()]).
% is_process_alive/1 checks liveness
case is_process_alive(Pid) of
true -> ok;
false -> {error, dead}
end.send (!) — Paso de Mensajes
Pid ! Msg envía asíncronamente un mensaje al buzón del destinatario. La entrega está garantizada y el orden se preserva entre el mismo par de procesos. ! devuelve el mensaje, permitiendo broadcasts. Los procesos pueden registrarse bajo un nombre átomo.
% Send a message: Pid ! Message
Pid ! {hello, self()}.
Pid ! ping.
Pid ! {compute, 1, 2, 3}.
% ! always returns the message itself, so you can broadcast:
[ P ! broadcast || P <- AllPids ].
% Send to a registered process (by atom name)
registered_name ! {request, Ref, self()}.
% Register / unregister a name for a PID
register(server, Pid).
unregister(server).
whereis(server). %=> Pid | undefinedreceive — Mensajes por Pattern Matching
receive escanea el buzón en orden buscando el primer mensaje que coincida; si ninguno coincide se suspende. La cláusula after establece un timeout (0 = no bloqueante, infinity = para siempre). Un patrón común es un loop() tail-recursivo que se llama a sí mismo.
% receive blocks until a matching message arrives
loop() ->
receive
{ping, From} ->
From ! pong,
loop();
{echo, Msg} ->
io:format("echo: ~p~n", [Msg]),
loop();
stop ->
ok
end.
% receive with a timeout
receive
{data, X} -> process(X)
after 5000 ->
{error, timeout}
end.
% Flush mailbox (drain all messages)
flush() ->
receive _ -> flush() after 0 -> ok end.Receive Selectivo y No Selectivo
receive es selectivo: busca el primer mensaje coincidente aunque existan mensajes más antiguos. Ideal para matching de respuestas específicas (con Ref único), pero los mensajes no coincidentes se acumulan y ralentizan los escaneos. gen_server evita esto.
% Selective receive: skips non-matching messages
get_reply(Ref) ->
receive
{Ref, Reply} -> Reply % only matches the reply with our Ref
after 5000 ->
{error, timeout}
end.
% Problem: other messages stay in the mailbox, slowing future receives.
% For high-throughput servers use a selective receive library or
% gen_server (which keeps its mailbox clean).
% Non-selective (drain in order):
drain_all() ->
receive
Msg -> [Msg | drain_all()]
after 0 ->
[]
end.Petición / Respuesta con Referencias
El patrón call empareja cada petición con una referencia única (make_ref/0). El cliente envía {call, Ref, self(), Request} y espera una respuesta etiquetada con el mismo Ref. Es la base de gen_server:call.
% Client: send a tagged request, await the matching reply
call(Server, Request) ->
Ref = make_ref(),
Server ! {call, Ref, self(), Request},
receive
{Ref, Reply} -> Reply
after 5000 ->
exit(timeout)
end.
% Server side:
handle({call, Ref, From, Request}, State) ->
Reply = do_work(Request),
From ! {Ref, Reply},
State.Recursión de Cola y Bucle de Servidor
Los procesos BEAM mantienen estado mediante recursión de cola: el bucle se llama a sí mismo con el nuevo estado como última expresión, sin crecer la pila. Cada cláusula receive termina con una llamada de cola a loop/1 con el estado actualizado.
% A counter server — each message mutates state via recursion
start_counter(Init) -> spawn(fun() -> counter_loop(Init) end).
counter_loop(N) ->
receive
inc -> counter_loop(N + 1);
dec -> counter_loop(N - 1);
{get, From} -> From ! {value, N}, counter_loop(N);
reset -> counter_loop(0)
end.
% Caller:
Pid = start_counter(0).
Pid ! inc.
Pid ! {get, self()}.
receive {value, V} -> io:format("count = ~p~n", [V]) end.Enlaces, Monitores y Errores
link / unlink — Enlace Bidireccional
link/1 crea un enlace bidireccional: si un proceso termina, el otro recibe una señal de salida. Por defecto esa señal también interrumpe al receptor. process_flag(trap_exit, true) convierte señales en mensajes {'EXIT', From, Reason}. spawn_link/1 hace ambos atómicamente.
% link/1 links current process to another
Pid = spawn(fun() -> ... end),
link(Pid).
% If either dies, the other gets an exit signal.
% Default behavior: the linked partner also exits.
% spawn_link does both atomically:
Pid = spawn_link(fun() -> ... end).
% Trap exits to convert death signals into messages:
process_flag(trap_exit, true).
receive
{'EXIT', From, Reason} -> io:format("~p died: ~p~n", [From, Reason])
end.
unlink(Pid). % remove the link (best-effort)monitor / demonitor — Monitor Unidireccional
monitor(process, Pid) es unidireccional: solo el llamador recibe un mensaje 'DOWN'. Preferible a link cuando solo se quiere observar. Cada monitor devuelve un Ref único para distinguir múltiples monitores.
% monitor/1: one-way — we observe Pid, but it doesn't observe us
Ref = monitor(process, Pid).
% If Pid dies, we receive:
% {'DOWN', Ref, process, Pid, Reason}
receive
{'DOWN', Ref, process, Pid, normal} -> ok;
{'DOWN', Ref, process, Pid, Reason} -> {error, Reason}
end.
% demonitor/1 removes the monitor
demonitor(Ref).
% demonitor/2 with [flush] also drains any pending 'DOWN' message
demonitor(Ref, [flush]).Señales exit y Razones
exit(Reason) termina el proceso actual; exit(Pid, Reason) envía una señal a Pid. La razón importa: normal y shutdown no se propagan, otras se propagan y matan a los enlazados (salvo que capturen). kill es intraptable — último recurso.
% Send an exit signal explicitly:
exit(Pid, Reason). % tell Pid to exit with Reason
% Terminate the current process:
exit(Reason). % Reason != normal kills linked partners
% exit/2 with the atom 'kill' is untrappable:
exit(Pid, kill). % Pid dies even if it traps exits.
% (Only the kernel-supervised 'kill' reason cannot be trapped.)
% Reasons:
% normal -> linked partners do NOT die
% shutdown -> linked partners do NOT die (used in graceful stop)
% {shutdown, Term} -> graceful with reason, also non-propagating
% anything else -> linked partners also die (unless trapping)try / catch y Excepciones
try ... catch Class:Reason maneja tres clases: throw (throw/1 explícito), error (errores runtime), exit (exit/1). La cláusula after siempre se ejecuta para limpieza. erlang:get_stacktrace() captura la traza de pila.
try
{ok, Bin} = file:read_file(Path),
binary_to_list(Bin)
catch
throw:Term -> {thrown, Term};
error:Reason -> {error, Reason, erlang:get_stacktrace()};
exit:Reason -> {exit, Reason}
after
% always runs (cleanup), regardless of success/failure
file:close(Fd)
end.
% Raise exceptions:
throw({bad, Value}). % catchable as throw
erlang:error(badarg). % catchable as error
exit(timeout). % catchable as exitPatrón Supervisor (Manual)
Un supervisor captura exits, inicia su hijo con spawn_link y al recibir {'EXIT', Pid, _} lo reinicia. La filosofía «let it crash» —supervisor simple, workers que fallan rápido— es el corazón de la tolerancia a fallos de Erlang.
% A minimal supervisor: start a child, restart on death
start_sup(Mod) ->
process_flag(trap_exit, true),
Pid = spawn_link(fun() -> Mod:run() end),
sup_loop(Mod, Pid).
sup_loop(Mod, Pid) ->
receive
{'EXIT', Pid, Reason} ->
io:format("child died ~p, restarting~n", [Reason]),
NewPid = spawn_link(fun() -> Mod:run() end),
sup_loop(Mod, NewPid);
{stop, From} ->
exit(Pid, shutdown),
From ! ok
end.OTP gen_server (Breve)
Esqueleto del Behaviour gen_server
Implementar -behaviour(gen_server) hace que el compilador verifique las funciones callback requeridas. El estado fluye por init/1 -> handle_call/3 (síncrono) / handle_cast/2 (asíncrono) -> terminate/2. {local, Name} permite llamar por átomo.
-module(counter).
-behaviour(gen_server).
-export([start_link/0, inc/0, get/0]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []).
inc() -> gen_server:cast(?MODULE, inc).
get() -> gen_server:call(?MODULE, get).
init(N) -> {ok, N}.
handle_call(get, _F, N) -> {reply, N, N}.
handle_cast(inc, N) -> {noreply, N + 1}.
handle_info(_, N) -> {noreply, N}.
terminate(_, _) -> ok.
code_change(_, N, _) -> {ok, N}.call vs cast
call es síncrono y bloquea al llamador hasta que el servidor responde (o timeout 5s). cast es asíncrono y siempre devuelve ok inmediatamente. call se basa en el patrón petición/respuesta con referencia.
% Synchronous call — waits for reply, crashes on server death
{ok, Value} = gen_server:call(Server, {get, Key}).
% Asynchronous cast — fire and forget
ok = gen_server:cast(Server, {put, Key, Value}).
% Call supports timeout and monitor under the hood:
gen_server:call(Server, Req, 5000).
% Server replies in handle_call:
handle_call({get, Key}, From, State) ->
{reply, maps:get(Key, State), State}.
% handle_cast never replies:
handle_cast({put, K, V}, State) ->
{noreply, maps:put(K, V, State)}.handle_info y Otros Callbacks
handle_info/2 captura mensajes no call/cast — cualquier Pid ! Msg, 'DOWN', timeouts y datos de socket. terminate/2 libera recursos (no garantizado en kill brusco). code_change/3 habilita la famosa actualización de código en caliente.
% handle_info/2 handles messages NOT from call/cast:
% - plain messages from other processes (Pid ! Msg)
% - 'DOWN' messages from monitors
% - timeouts sent by gen_server:start(..., Timeout)
handle_info({'DOWN', Ref, process, Pid, Reason}, State) ->
io:format("monitored ~p died: ~p~n", [Pid, Reason]),
{noreply, State};
handle_info({tcp, Socket, Data}, State) ->
%% handle incoming socket data
{noreply, State};
handle_info(Info, State) ->
{noreply, State}.
% terminate/2 runs on shutdown — close fds, flush, etc.
terminate(Reason, State) ->
io:format("shutting down: ~p~n", [Reason]),
ok.
% code_change/3 enables hot code upgrade.
code_change(_OldVsn, State, _Extra) -> {ok, State}.Estructura de Aplicación (OTP)
Una aplicación OTP es un componente autocontenido con un .app que describe módulos, dependencias y módulo de entrada (mod). start/2 devuelve el PID del supervisor superior. Los releases empaquetan aplicaciones en un sistema ejecutable.
% myapp.app — application resource file
{application, myapp,
[{description, "Demo app"},
{vsn, "1.0.0"},
{modules, [myapp_app, myapp_sup, counter]},
{registered, [myapp_sup]},
{applications, [kernel, stdlib]},
{mod, {myapp_app, []}},
{env, [{port, 4000}]}
]}.
% myapp_app.erl — application behaviour
-module(myapp_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) -> myapp_sup:start_link().
stop(_State) -> ok.
% Start everything:
% application:start(myapp).
% Or with release: erl -eval 'application:ensure_all_started(myapp)'Fragmentos de Erlang relacionados
Copy-paste ready code for common tasks.
Procesos Ping-Pong
Dos procesos se pasan mensajes usando spawn y receive.
Contador con gen_server
Construye un servidor con estado con el behaviour gen_server.
Árbol de supervisores
Define un supervisor que inicia workers y los reinicia al caer.
Receive selectivo con referencias
Extrae una respuesta específica de entre muchos mensajes usando una referencia única.
Enlaces, captura de exit y 'let it crash'
Usa link y trap_exit para detectar la muerte de procesos y recuperarse.
Servidor con estado vía recursión de cola
Mantiene estado mutable en un proceso hilándolo a través de llamadas recursivas.
Mapa paralelo con rpc:pmap
Aplica una función a cada elemento de una lista en paralelo entre procesos.
Actualización de código en caliente
Recarga el código de un módulo sin detener el sistema en ejecución.
Was this helpful?