For the next few weeks I’m gonna list cool features and tips for every programming language You can imagine. From most popular like Java or Python, through new emerging flagship killers - Scala, Go, Rust - and these which were designed years ago but still fullfil their niche f.i Lisp, Erlang or Prolog.

Erlang

Erlang is (un)widely known from it’s easiness of building distributed systems. A system written in Erlang can run great, despite being deployed on one, two or hundred machines. But even though it’s amazing in it’s particular niche, it also has unique syntax solutions that make it nice to develop in.

Pattern matching

Some of You might be familiar with pattern matching, some of You can’t imagine programming without it, but most of imperative programmers aren’t so familiar with the concept at all. Pattern matching is a conditional assignment. What does it mean? That means that an assignment fails if the arguments don’t meet the requirement. A simplest possible pattern matching example is an overloaded function.

Although the nameType() function has the same name twice when we call nameType(1) we execute totally different function than if we typed nameType("1"). This is pattern matching in it’s most primitive form.

Now, if You don’t know yet, Erlang is a functional language - which basically means it embraces lack of side-effects (changes in global state). Because of that, variables in Erlang are ‘single-assignment variables’ (Something like finals in Java, vals in Scala or readonlys in C#).
And also in Erlang every assignment is pattern-matching.

But we can also use that with destructuring asigment.

Or function definition

Now imagine we want to write a simple program that checks if X and Y coords of a point are equal. Take a simple Java example

Not quite what we want. Simple concept of implementing point and comparing X and Y took us 14 lines of code.

Now let’s see Erlang equivalent

That’s a little bit better, isn’t it?

Bonus

Erlang can also pattern match on Lists with [Head|Tail] behaviour. Imagine we want to check if the nunber contains digits in pairs (11223355, 1122, 88 ; but not 123, 112 or 556612)

It’s not that long, but definitelly not easy to reason about. Now let’s try Erlang equivalent

Imperative version is probably understandable for programming folks so I will just describe the functional one.

We’ve made the whole solution using 5 simple statements

1. If A is an integer, cast it to a string (lists and strings are the same in Erlang) and execute the function as it were a string in the first place.
2. If A hasn’t got even length we know the statement is false.
3. If parameter is empty list the statement is true
4. If first and second elements are the same return true AND result of the same logic on the rest of the list
5. If none of the above applies, the statement is false

You may argue which solution is better in different dimensions. But in my opinion Erlang version is much easier to understand.