Erlang中的匹配模式總結(jié)
一、賦值時(shí)匹配
原子匹配
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]
參數(shù)匹配
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 中的模式匹配總結(jié)"
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 % 匹配所有其它結(jié)果
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}}
相關(guān)文章
Erlang中的注冊(cè)進(jìn)程使用實(shí)例
這篇文章主要介紹了Erlang中的注冊(cè)進(jìn)程使用實(shí)例,本文給出正常進(jìn)程通信實(shí)例和使用使用注冊(cè)進(jìn)程通信實(shí)例,需要的朋友可以參考下2015-02-02Erlang中執(zhí)行l(wèi)inux命令的兩種方法
這篇文章主要介紹了Erlang中執(zhí)行l(wèi)inux命令的兩種方法,本文著重講解了erlang:open_port的使用,需要的朋友可以參考下2015-01-01Erlang程序設(shè)計(jì)(第2版)讀書(shū)筆記:Erlang安裝和基礎(chǔ)語(yǔ)法
這篇文章主要介紹了Erlang程序設(shè)計(jì)(第2版)讀書(shū)筆記:Erlang安裝和基礎(chǔ)語(yǔ)法,需要的朋友可以參考下2015-02-02Erlang語(yǔ)法學(xué)習(xí)筆記:變量、原子、元組、列表、字符串
這篇文章主要介紹了Erlang語(yǔ)法學(xué)習(xí)筆記:變量、原子、元組、列表、字符串,本文簡(jiǎn)明總結(jié)了這5種類(lèi)型的相關(guān)知識(shí),需要的朋友可以參考下2015-01-01Erlang項(xiàng)目?jī)?nèi)存泄漏分析方法
這篇文章主要介紹了Erlang項(xiàng)目?jī)?nèi)存泄漏分析方法,本文講解了分析方法、分析流程并找到問(wèn)題原因和解決方法,需要的朋友可以參考下2015-02-02