Home > DeveloperSection > Beginner > Pattern Matching in Erlang

Pattern Matching in Erlang

erlang erlang 
0 Comment(s)
 1599  View(s)
Rate this:

Pattern Matching in Erlang

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==lion ->"roar";
true -> "animal not exist in pattern"
{A, "says " ++ Speak ++ "!"}.

Don't want to miss updates? Please click the below button!

Follow MindStick