Erlang中的匹配模式总结

2019-11-06 09:26:23丽君

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