Skip to content

Instantly share code, notes, and snippets.

@mvoto
Last active May 28, 2018 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvoto/40bdd4edd419d341d52750929825c1e8 to your computer and use it in GitHub Desktop.
Save mvoto/40bdd4edd419d341d52750929825c1e8 to your computer and use it in GitHub Desktop.

References:

Roadmap:

1 - Syntax - pipe operator / collections 2 - Pattern Matching + pin operator(^) 3 - Basic Recursion, map, reduce, tail recursion - collections + enums 4 - Concurrency / Distributed systems

Pattern Matching

Equals sign here is different, is not an assignment, is more like an assertion: it succeeds if elixir can find a way of making the left-hand side equal the right-hand side(reason to be called a match operator). A simple example:

a = 1
> 1

1 = a
> 1

2 = a
** (MatchError) no match of right hand side value: 2

At the first line, a = 1 was an assertion, so now a has value 1. At the second line, 1 = a was another assertion, since a had value 1. The last line tries to match 2 = a which is not an assertion and raises that error.

What if you run:

a = 2
> 2

Hmm, interesting, it assigned 2 on a because it was an assertion, so what if we want to keep the previously "assigned" value ? Well, you can use the pin operator for that:

a = 3
> 3

^a = 1
** (MatchError) no match of right hand side value: 1

The pin operator basically forces elixir to keep the existing value of the variable. The same things work for diofferent matches:


Brainstorm:

Some people say that elixir is easy to learn if you come from ruby, because of its background - the creator José Valim was part of rails core team - but it's not that simple, some other people advice to avoid writing ruby in elixir. A better advice would be: avoid writing OO in FP. FP understanding is essential to write elixir code, but I will not dive deep into that, because it's a huge topic, definitely for a future post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment