Learning Erlang L1

Todays goal: Don't understand it. Don't try to perfect it. Just use it.

Learning Erlang L1
Photo by Element5 Digital / Unsplash

Todays goal: Don't understand it. Don't try to perfect it. Just use it.

Start your Erlang Container.
You should see something like

Erlang/OTP 28 [erts-16.4] [source] [64-bit] [smp:128:4] [ds:128:4:10] [...]

Eshell V16.4 (press Ctrl+G to abort, type help(). for help)
1>

That's your playground πŸ™‚

Let's start experimenting.

2 + 3.
πŸ’‘
Important: Period at the end
X = 5.
X.
X = 6.
πŸ‘‰
This HAS to fail.
This is your first encounter with immutability.

First function:

Double = fun(X) -> X * 2 end.
Double(4).
πŸ’‘
This is an anonymous function.

Using a list:

[1,2,3].
hd([1,2,3]).
tl([1,2,3]).

Aha-moment?

[Head | Tail] = [1,2,3].
Head.
Tail.
πŸ‘‰
This is pattern matching in action. And this is one of the most important concepts of all.

Some more fun with fun() πŸ˜‰

Square = fun(X) -> X * X end.
Square(5).

Try deliberately breaking something:
wrong type
wrong pattern

Triple = fun(X) -> X * 3 end.

Functions are simply values.

Use pattern matching

IsZero = fun
    (0) -> true;
    (_) -> false
end.

Test it:

  • IsZero(0)
  • IsZero(5)

Try deliberately breaking something:

  • IsZero("0")

Subscribe to Michels Blog

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe