articles

Home / DeveloperSection / Articles / Pattern Matching in Erlang

Pattern Matching in Erlang

Sunil Singh 5210 14-Sep-2015
Pattern matching is a process of checking a given sequence of tokens for the presence of the constituents of some pattern . Erlang uses pattern matching to bind variables to values. In erlang pattern matching can be explicit as well as implicit .

Explicit pattern matching example is given below-

Num = 10,
[Num1,Num2,Num3,Num4] = [1,2,3,4],
[P1,P2|P3] = [1,2,3,4,5,6,7],
In the above example Num=10 is  explicit pattern matching Value 10 is assigned to Num we can not re-assign different value to erlang variables,one time assignment is allowed.In the second line Num1,Num2,Num3 and Num4 have values 1,2 and so on,this is explicit pattern matching. P1 have value 1,P2 have value 2 and P have values [3,4,5,6,7].Implicit pattern matching occurred in function calls.
Guard Patterns matching is given below-

erlang_pattern_matching(A) ->
Speak = if A == cat -> "meow";
A == frog -> "croak";
A == dog -> "bark";
A == bee -> "buzz";
A==elephant->"trumpet";
A==snake->"hiss";
A==sheep->"bleat";
A==lion ->"roar";
A==swan->"cry";
true -> "animal not exist in pattern"
end,
{A, "says " ++ Speak ++ "!"}.

Updated 27-Mar-2018

Leave Comment

Comments

Liked By