Sijin T V
Sijin T V A passionate Software Engineer who contributes to the wonders happenning on the internet

Pattern Matching and Array Destructuring - Functional Programming

Pattern matching is a powerful concept used with Functional Programing. It is actually a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts.

Lets see some examples

Elixir
1
2
3
4
5
6
7
8
iex> [a, b, c] = [:hello, "world", 12]
[:hello, "world", 42]
iex> a
:hello
iex> b
"world"
iex> c
42

It should not be mistaken for multiple assignment in Ruby. In pattern matching the = operator checks whether the values get matched as well.

which means

1
2
3
4
5
6
7
8
9
10
11
12
13
14
iex> [a, b] = [] #left and right number of values are different
 ** (MatchError) no match of right hand side value: []

iex> {:ok, result} = {:ok, 13}
{:ok, 13}
iex> result
13

iex> {:ok, result} = {:error, :oops} #left side will only match the right side when the right side is a tuple that starts with the atom
** (MatchError) no match of right hand side value: {:error, :oops}


iex> {a, b, c} = [:hello, "world", 42] #mistatched data type
** (MatchError) no match of right hand side value: [:hello, "world", 42]

the above all will throw an error.

In lists we can also do

1
2
3
4
5
6
 iex> [head | tail] = [1, 2, 3]
[1, 2, 3]
iex> head
1
iex> tail
[2, 3]

Which is quite useful for easy destructure and prepending items to a list as well.

1
2
3
4
iex> list = [1, 2, 3]
[1, 2, 3]
iex> [0 | list]
[0, 1, 2, 3]
Javascript

In JS, pattern matching concept is indroduced via Array and Object Destructuring.

For example:

1
2
3
const colors = ['red', 'orange', 'green'];

const [red, orange, green] = vehicles;

Also

1
2
3
4
5
6
7
8
9
10
11
12
13
const vehicleOne = {
  brand: 'Ford',
  model: 'Mustang',
  type: 'car',
  year: 2021, 
  color: 'red'
}

myVehicle(vehicleOne);

function myVehicle({type, color, brand, model}) {// Destructured here
  const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}

which is quite useful.

comments powered by Disqus