Learn Essential Elixir [Part 1]

February 19, 2020

NOTE: This is a cross-post from my newsletter. I publish each email one week after it’s sent. Subscribe to get more content like this earlier right in your inbox! 💌

Hi ! In this post, I’ll try to teach you Elixir in a few posts, and to not waste time, let’s start right away.

I assume that you already installed Elixir. (If you didn’t yet, Google is your friend, and if you find any issues with installation, Tweet me @RxAssim)

Hello world

Execute the iex command in your terminal and write:

defmodule Greeter do
    def greet(name) do
        IO.puts("Hello, " <> name)
    end
end

then call the function using Greeter.greet("World"). The output should be:

Hello World
:ok

Binding

In Elixir, a = 1 is not called an assignment, it’s called binding. We bind the value 1 to the variable a.

Maps

To create a new map:

dog = %{
    name: "Max",
    age: 5,
    owner: "Jack"
}

To access an attribute in a map:

dog_name = dog.name

Lists

To create a new list:

dogs = ["Max", "Ronda", "Willy", "Pika"]

Pattern Matching

This is one of my favorite things in Elixir. Let’s say you have the dog map you defined above, and you want to extract the name from it.

You could either use dog.name OR you could pattern match it like this:

%{name: dog_name} = dog

and if you execute IO.puts(dog_name) guess what you’Il get…: "Max" which is the same value you’d get with dog.name.

Pattern Matching in functions

def eat(%{meal: today_s_meal}) do
    IO.puts("I want to eat "<> today_s_meal)
end

The function above accepts a Map as an argument that has the meal attribute. If you call the function with anything other than such a Map, It’Il throw an error.

Piping

let’s consider thess functions:

def cook(meal) do
    IO.puts("Cooked "<> meal)
end
def eat(cooked_meal) do
    IO.puts("I ate " <> cooked_meal)
end

Now if we want to output I ate cooked sushi we’d either do:

eat(cook("sushi"))

OR we’Il use the Pipe operator:

"sushi"
|> cook
|> eat

Et Voilà !

That’s it for part 1, sign up to my newsletter to get notified when I drop the other parts. Peace.

Join the Newsletter

Subscribe to get my latest content by email.

    Unsubscribe at any time.