Getting Started with Elixir Programming Language

2017-05-15 11 min read GuestPost Learning Uncategorized

If you have been reading blog posts, hacker news threads, your favorite developers tweets or listening to podcasts, at this point you’ve probably heard about the Elixir programming language. The language was created by José Valim, a well known developer in the open-source world. You may know him from the Ruby on Rails MVC framework or from devise and simple_form ruby gems him and his co-workers from the Plataformatec have been working on in the last few years.

According the José Valim, Elixir was born in 2011. He had the idea to build the new language due the lack of good tools to solve the concurrency problems in the ruby world. At that time, after spending time studying concurrency and distributed focused languages, he found two languages that he liked, Erlang and Clojure which run in the JVM. He liked everything he saw in the Erlang language (Erlang VM) and he hated the things he didn’t see, like polymorphism, metaprogramming and language extendability attributes which Clojure was good at. So, Elixir was born with that in mind, to have an alternative for Clojure and a dynamic language which runs in the Erlang Virtual Machine with good extendability support.

Getting Started with Elixir Programming Language

Elixir describes itself as a dynamic, functional language with immutable state and an actor based approach to concurrency designed for building scalable and maintainable applications with a simple, modern and tidy syntax. The language runs in the Erlang Virtual Machine, a battle proof, high-performance and distributed virtual machine known for its low latency and fault tolerance characteristics.

Before we see some code, it’s worth saying that Elixir has been accepted by the community which is growing. If you want to learn Elixir today you will easily find books, libraries, conferences, meetups, podcasts, blog posts, newsletters and all sorts of learning sources out there as well as it was accepted by the Erlang creators.

Let’s see some code!

Install Elixir:

Installing Elixir is super easy in all major platforms and is an one-liner in most of them.

Arch Linux

Elixir is available on Arch Linux through the official repositories:

1
pacman -S elixir

Ubuntu

Installing Elixir in Ubuntu is a bit tidious. But it is easy enough nonetheless.

1
2
3
4
wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
apt-get update
apt-get install esl-erlang
apt-get install elixir

OS X

Install Elixir in OS X using Homebrew.

1
brew install elixir

Meet IEx

After the installation is completed, it’s time to open your shell. You will spend a lot of time in your shell if you want to develop in Elixir.

Elixir’s interactive shell or IEx is a REPL – (Read Evaluate Print Loop) where you can explore Elixir. You can input expressions there and they will be evaluated giving you immediate feedback. Keep in mind that your code is truly evaluated and not compiled, so make sure not to run profiling nor benchmarks in the shell.

The Break Command

There’s an important thing you need to know before you start the IEx RELP – how to exit it.

You’re probably used to hitting

  <td>
    <div class="text codecolorer">
      CTRL+C
    </div>
  </td>
</tr>
1

to close the programs running in the terminal. If you hit

  <td>
    <div class="text codecolorer">
      CTRL+C
    </div>
  </td>
</tr>
1

in the IEx RELP, you will open up the Break Menu. Once in the break menu, you can hit

  <td>
    <div class="text codecolorer">
      CTRL+C
    </div>
  </td>
</tr>
1

again to quit the shell as well as pressing

  <td>
    <div class="text codecolorer">
      a
    </div>
  </td>
</tr>
1

.

I’m not going to dive into the break menu functions. But, let’s see a few IEx helpers!

Helpers

IEx provides a bunch of helpers, in order to list all of them type:

  <td>
    <div class="text codecolorer">
      h()
    </div>
  </td>
</tr>
1

.

And this is what you should see:

Those are some of my favorites, I think they will be yours as well.

  •   <td>
        <div class="text codecolorer">
          h
        </div>
      </td>
    </tr>
    
    1

    as we just saw, this function will print the helper message.

    •   <td>
          <div class="text codecolorer">
            h/1
          </div>
        </td>
      </tr>
      
      1

      which is the same function, but now it expects one argument.

    For instance, whenever you want to see the documentation of the

      <td>
        <div class="text codecolorer">
          String
        </div>
      </td>
    </tr>
    
    1
      <td>
        <div class="text codecolorer">
          strip/2
        </div>
      </td>
    </tr>
    
    1

    method you can easily do:

    Probably the second most useful IEx helper you’re going to use while programming in Elixir is the
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              c/2
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    , which compiles a given elixir file (or a list) and expects as a second parameter a path to write the compiled files to.
    
    Let’s say you are working in one of the http://exercism.io/ Elixir exersices, the Anagram exercise.
    
    So you have implemented the
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              Anagram
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    module, which has the method
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              match/2
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    in the anagram.exs file. As the good [developer][1] you are, you have written a few specs to make sure everything works as expected as well.
    
    This is how your current directory looks:
    Now, in order to run your tests against the Anagram module you need to run/compile the tests.
    As you just saw, in order to compile a file, simply invoke the
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              elixir
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    executable passing as argument path to the file you want to compile.
    
    Now let’s say you want to run the IEx REPL with the Anagram module accessible in the session context. There are two commonly used options. The first is you can require the file by using the options
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              -r
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    , something like
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              iex -r anagram.exs
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    . The second one, you can compile right from the IEx session.
    Simple, just like that!
    
    Ok, what about if you want to recompile a module? Should you exit the IEx, run it again and compile the file again? Nope! If you have a good memory, you will remember that when we listed all the helpers available in the IEx RELP, we saw something about a recompile command. Let’s see how it works.
    Notice that this time, you passed as an argument the module itself and not the file path.
    
    As we saw, IEx has a bunch of other useful helpers that will help you learn and understand better how an Elixir program works.
    
    ## Basics of Elixir Types {#basics-of-elixir-types}
    
    ### Numbers {#numbers}
    
    There are two types of numbers. Arbitrary sized integers and floating points numbers.
    
    #### Integers {#integers}
    
    Integers can be written in the decimal base, hexadecimal, octal and binary.
    
    As in [Ruby][2], you can use underscore to separate groups of three digits when writing large numbers. For instance you could right a hundred million like this:
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      100_000_000
    </div>
  </td>
</tr>
1

    Octal:
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      0o444
    </div>
  </td>
</tr>
1

    Hexdecimal:
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      0xabc
    </div>
  </td>
</tr>
1

    Binary:
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      0b1011
    </div>
  </td>
</tr>
1

    #### Floats {#floats}
    
    Floare are IEEE 754 double precision. They have 16 digits of accuracy and a maximum exponent of around 10308.
    
    Floats are written using a decimal point. There must be at least one digit before and after the point. You can also append a trailing exponent. For instance 1.0, 0.3141589e1, and 314159.0-e.
    
    ### Atoms {#atoms}
    
    Atoms are constants that represent names. They are immutable values. You write an atom with a leading colon
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              :
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    and a sequence of letters, digits, underscores, and at signs
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              @
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    . You can also write them with a leading colon
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              :
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    and an arbitrary sequence of characters enclosed by quotes.
    
    Atoms are a very powerful tool, they are used to reference erlang functions as well as keys and Elixir methods.
    
    Here are a few valid atoms.
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      :name, :first_name, :"last name", &nbsp;:===, :is_it_@_question?
    </div>
  </td>
</tr>
1

    ### Booleans {#booleans}
    
    Of course, booleans are true and false values. But the nice thing about them is at the end of the day, they’re just atoms.
    ### Strings {#strings}
    
    By default, strings in Elixir are <a href="https://en.wikipedia.org/wiki/UTF-8" target="_blank" rel="noopener noreferrer">UTF-8</a> compliant. To use them you can have an arbitrary number of characters enclosed by
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              "
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    or
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              '
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    . You can also have interpolated expressions inside the string as well as escaped characters.
    Be aware that single quoted strings are actually a list of binaries.
    ### Anonymous Functions {#anonymous-functions}
    
    As a functional language, Elixir has anonymous functions as a basic type. A simple way to write a function is
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              fn (argument_list) -> body end
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    . But a function can have multiple bodies with multiple argument lists, guard clauses, and so on.
    
    Dave Thomas, in the <a href="https://pragprog.com/book/elixir/programming-elixir" target="_blank" rel="noopener noreferrer">Programming Elixir</a> book, suggests we think of fn…end as being the quotes that surround a string literal, where instead of returning a string value we are returning a function.
    ### Tuples {#tuples}
    
    Tuple is an immutable indexed array. They are fast to return its size and slow to append new values due its immutable nature. When updating a tuple, you are actually creating a whole new copy of the tuple self.
    
    Tuples are very often used as the return value of an array. While coding in Elixir you will very often see this,
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              {:ok, something_else_here}
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    .
    
    Here’s how we write a tuple:
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              {?a,?b,?c}
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    .
    
    ### Pattern Matching {#pattern-matching}
    
    I won’t be able to explain everything you need to know about Pattern Matching, however what you are about to read covers a lot of what you need to know to get started.
    
    Elixir uses
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              =
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    as a match operator. To understand this, we kind of need to unlearn what we know about
    
    <div class="codecolorer-container text solarized-light" style="overflow:auto;white-space:nowrap;width:550px;">
      <table cellspacing="0" cellpadding="0">
        <tr>
          <td class="line-numbers">
            <div>
              1<br />
            </div>
          </td>
          
          <td>
            <div class="text codecolorer">
              =
            </div>
          </td>
        </tr>
      </table>
    </div>
    
    in other traditional languages. In traditional languages the equals operator is for assignment. In Elixir, the equals operators is for pattern matching.
    
    So, that’s the way it works values in the left hand side. If they are variables they are bound to the right hand side, if they are not variables elixir tries to match them with the right hand side.
    #### Pin Operator {#pin-operator}
    
    Elixir provides a way to always force pattern matching against the variable in the left hand side, the pin operator.
    ### Lists {#lists}
    
    In Elixir, Lists look like arrays as we know it from other languages but they are not. Lists are linked structures which consist of a head and a tail.
    #### Keyword Lists {#keyword-lists}
    
    Keyword Lists are a list of Tuple pairs.
    
    You simply write them as lists. For instance: [{:one, 1}, 2, {:three, 3}]. There’s a shortcut for defining lists, here’s how it looks: [one: 1, three: 3].
    
    In order to retrieve an item from a keyword list you can either use:
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      Keyword.get([{:one, 1}, 2, {:three, 3}], :one)
    </div>
  </td>
</tr>
1

    Or use the shortcut:
    
    <pre><div class="codecolorer-container text solarized-light language-elixir" style="overflow:auto;white-space:nowrap;width:550px;">
  <td>
    <div class="text codecolorer">
      [{:one, 1}, 2, {:three, 3}][:one]
    </div>
  </td>
</tr>
1

    Because keyword lists are slow when retrieving a value, in it is an expensive operation, so if you are storing data that needs fast access you should use a Map.
    
    #### Maps {#maps}
    
    Maps are an efficient collection of key/value pairs. The key can have any value you want as a key, but usually should be the same type. Different from keyword lists, Maps allow only one entry for a given key. They are efficient as they grow and they can be used in the Elixir pattern matching in general use maps when you need an associative array.
    
    This <a href="https://www.toptal.com/elixir/getting-started-elixir-programming-language" target="_blank" rel="noopener noreferrer">article</a> originally appeared on <a href="https://www.toptal.com/elixir/" target="_blank" rel="noopener noreferrer">Toptal</a>
comments powered by Disqus