一、赋值时匹配
原子匹配
复制代码 代码如下:
atom = atom % atom
another = another % another
atom = another % exception error
变量匹配
复制代码 代码如下:
Var = 2. % 2
Var = 3 - 1. % 2
Var = 1. % exception error
元组匹配
复制代码 代码如下:
Attr = {name, sloger}. % {name, sloger}
{name, Name} = Attr. % {name, sloger}
Name. % sloger
列表匹配
复制代码 代码如下:
Langs = [perl, python, ruby, erlang].
[Head | Tail] = Langs.
Head. % perl
Tail. % [python, ruby, erlang]
参数匹配
复制代码 代码如下:
sum([]) -> 0;
sum([H|T]) -> H + sum(T).
sum([1, 2, 3]). % 6
记录匹配
复制代码 代码如下:
%% record(post, {title, slug, body, author}).
Post = #post{title = "Pattern Match in Erlang",
slug = "pattern-match-in-erlang",
body = "Bla bla bla...",
author = sloger}.
#post{title = Title, slug = Slug} = Post.
Title. % "Erlang 中的模式匹配总结"
Slug. % "summary-of-pattern-match-in-erlang"
比特匹配
复制代码 代码如下:
Red = 5.
Green = 23.
Blue = 200.
Color = <<Red:5, Green:6, Blue:5.
<<R1:5, G1:6, B1:5 = Color.
R1. % 5
G1. % 23
B1. % 200
二、流程控制中的匹配
if
复制代码 代码如下:
if
Pattern1 [when Guard1] -> Expression1;
Pattern2 [when Guard2] -> Expression2;
%% and so on ...
_ -> Expression3 % 匹配所有其它结果
end.
case
复制代码 代码如下:
case Expression of
Pattern1 [when Guard1] -> Expression1;
Pattern2 [when Guard2] -> Expression2;
%% and so on ...
_ -> Expression3
end.
try catch
复制代码 代码如下:
try FunctionOrExpressions of
Pattern1 [when Guard1] -> Expression1;
Pattern2 [when Guard2] -> Expression2
%% and so on ...
catch
ExType:ExPattern1 [when ExGuard1] ->
ExExpression1;
ExType:ExPattern2 [when ExGuard2] ->
ExExpression2;
%% and so on ...
_:_ -> DefaultExExpression % _:_ 匹配所有异常
after
AfterExpressions
end
消息传递匹配
复制代码 代码如下:
loop() ->
receive
{From, {rectangle, Width, Height}} ->
From ! {self(), Width * Height},
loop();
{From, {circle, R}} ->
From ! {self(), 3.14 * R * R},
loop();
{From, _Other} ->
From ! {self(), {error, unknown_shape}}
loop()
end.
Pid = spawn(fun loop/0).
Pid ! {self(), {rectangle, 10, 5}}. % {Pid, 50}
Pid ! {self(), {circle, 4}}. % {Pid, 50.24}
Pid ! {self(), {square, 10}}. % {Pid, {error, unknown_shape}}
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 刘德华《LOVEHOPE 希望 爱》香港首批豪华版[WAV+CUE][1.1G]
- 群星.1994-宝丽金超级孖宝2CD【宝丽金】【WAV+CUE】
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 龚玥《金装龚玥HQCD》头版限量[WAV+CUE]
- 任贤齐《任贤齐创作集 音乐旅行者》[WAV+CUE][1.1G]
- 群星《快乐巨星·百万畅销曲85》2CD[WAV+CUE][828M]
- 合集《IU 李知恩2009-2022所有歌曲合集》[FLAC][7.4G]
- 童丽-《民歌》紫银合金AQCD[WAV+CUE]
- 刀郎2024.08.30《山歌响起的地方》资中“知交”线上演唱会.mp4
- [爵士女声测试大碟]洁辛塔《秋叶)[SACD-WAV]
- 任贤齐《任贤齐创作集 音乐旅行者》[WAV+CUE][1.1G]
- 赵传《一颗滚石的25年》 2CD引进版[WAV+CUE][1.6G]
- 群星《往岁乘霄》[320K/MP3][39.84MB]
- 群星《往岁乘霄》[FLAC/分轨][211.79MB]
- 群星.2024-JamboMedley(BEYOND40周年致敬2)【Kinns】【FLAC分轨】