基础
Hello World 与模块
每个 Erlang 文件都是一个用 -module(name) 声明的模块。导出函数用 -export([name/arity]) 列出。arity(参数个数)是函数标识的一部分——greet/0 和 greet/1 是不同的函数。在 shell 中用 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!变量与原子
变量以大写字母(或 _)开头,且只能单次赋值——一旦绑定就不能改变。对已绑定变量重新匹配实际上是一个断言:X = X+1 会引发 badmatch 错误。原子是以小写字母开头的命名常量;它们存储在全局表中,按身份比较。
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 discards元组与记录
元组是固定大小的容器,写作 {a,b,c}。记录是带命名字段的元组,用 -record 声明。更新记录字段会创建新记录(不可变数据)。第一个元素按惯例是标签原子(如 point 或 person),以便更清晰的模式匹配。
% 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 tuple列表与列表推导
列表是用 [Head|Tail] 构建的单向链表。++ 连接(左侧 O(n)),-- 移除元素。列表推导 [Expr || 限定符1, 限定符2, ...] 支持生成器(X <- List)和过滤器(布尔表达式)。它们是转换列表的习惯写法。
[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 product函数与模式匹配
函数定义为多个由 ; 分隔的子句,以句点终止。子句按顺序尝试,第一个模式和守卫都匹配的被选中。带标签的元组如 {ok, Val} / {error, Reason} 是不用异常表示成功/失败的标准方式。
-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}.映射
映射(自 R17 起)是键值字典。用 => 设置/插入(不存在则创建),用 := 更新(键必须已存在)。模式匹配中只允许 :=。maps:get/2 在键缺失时引发 badarg;用 maps:get/3 获取默认值或 maps:find/2 获取 {ok,_}|error 元组。
% 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.模式匹配与守卫
函数头中的模式匹配
Erlang 通过自上而下匹配参数来选择函数子句。模式可以绑定新变量、对字面量或已绑定变量断言相等,以及用 _ 忽略字段。同样的机制用于 receive、case 和 =。
% 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.case 表达式
case 求值一个表达式并将其与一系列模式匹配。每个子句可以有守卫。当函数分支依赖计算值而非原始参数时,它是标准控制流工具。除非想对意外输入崩溃,否则总应包含 _ 全匹配子句。
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.守卫
守卫限制子句何时匹配。它们限于已知的内置函数集合,因此总能终止且无副作用。逗号 = AND,分号 = OR。守卫在守卫序列中会被重新求值,因此尽量优先用模式匹配。
% 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!)