Skip to content

Instantly share code, notes, and snippets.

@klebervirgilio
Last active April 1, 2016 15:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klebervirgilio/eca01a4e116b15abc793 to your computer and use it in GitHub Desktop.
Save klebervirgilio/eca01a4e116b15abc793 to your computer and use it in GitHub Desktop.

Getting started with Elixir - Part 1

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

Elixir, a brief history

According the José Valim, the language was born 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 likes Erlang and Clojure which runs 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/is good at. So, Elixir was born with that in mind, have an alternative for Clojure and a dynamic language which runs in the Erlang Vitrual Machine with good extendability support.

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 Elarng Vitrual Machine, a battle proof, high-performance and distributed virtual machine known for its low latency and fault tolerance characteristics.

Before we show see some code, it's worth to say that Elixir has been accepted by the community which are growing. If you want to learn Elixir today you will easily find books, libraries, conferences, meetups, podcasts, blogs post, newsletters and all sort of learning sources out there as well as it was accepted by the Erlang creators. Quoting Joe Armstrong "This is good shit". https://joearms.github.io/2013/05/31/a-week-with-elixir.html

Cool! Let's see some code!

Install Elixir:

http://elixir-lang.org/install.html

Meet IEx

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

Elixir’s interactive shell or IEx is a RELP - (Read Evaluate Loop Print) 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 to not run profiling nor benchmarks in the shell.

img

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 hit CTRL+C to close the programs running in the terminal. If you hit CTRL+C in the IEx RELP, you will open up the Break Menu. Once in the break menu, you can hit CTRL+C again to quit the shell as well as hit a.

img

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

Helpers

IEx provides a bunch of helpers, in order to list all of them type: h() And that's what you should see:

img

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

  • h as we just saw, this function will print the helper message.
  • h/1 which is the same function, but now it expect one argument

So, for instance whenever you want to see the documentation of the String strip/2 method you can easily do:

Probably, the second most useful IEx helper you're going to use while programming in Elixir is the c/2 which will compiles a given elixir file (or a list) and expect 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 Anagram module, which has the method match/2 in the anagram.exs file plus, as the good developer you are you have written a few specs to make sure everything works as expected as well.

This is how your current directory looks like:

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 elixir executable passing as argument the 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 common used options, the first you can require the file by using the options -r. Something like that: iex -r anagram.exs and the second one you can compile the from the IEx session.

Simple 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 others useful helpers that will help you learn and understand better how an Elixir program works.

Basics of Elixir Types

Numbers

There are two types of numbers arbitrary sized integers and floating points numbers.

Integers

Integers can be written in the decimal base, hexadecimal, octal and binary.

As in ruby, you can use underscore to separate groups of three digits when writing large numbers. For instance you could right a hundred million like that.

100_000_000

Octal

0o444

Hexdecimal

0xabc

Binary

0b1011
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, are constants that represents name. They are immutable values. You write an atom with a leading colon : and a sequence of letters, digits, underscores, and at signs @. You can also write them with a leading colon : and an arbitrary sequence of characters enclosed by quotes.

Atoms is a very powerful tool, they are used to reference erlang functions, as well keys and Elixir methods.

Here are a few valid of atoms.

:name, :first_name, :"last name",  :===, :is_it_@_question?

Booleans

Of course, booleans are truthy and falsy values. But the nice thing about them is at the end of the day, they're just atoms.

Strings

By default strings in Elixir are UTF-8 compliance. To use them you can have an arbitrary number of characters enclosed by " or '. 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

As a functional language, Elixir has anonymous functions as a basic type. A simple way to write a function is fn (argument_list) -> body end. But a function can have multiple bodies with multiple argument lists and guard clauses, etc.

Dave Thomas, in the Programming Elixir 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

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 {:ok, something_else_here}

Here's how we write a tuple: {?a,?b,?c}

Pattern Matching

I don't assume I'm going to 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 = as a match operator. To understand we kind need to unlearn what we know about = in other traditional languages. In traditional languages the equals operators 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

Elixir provides a way to always force pattern matching against the variable in the left hand side. The pin operator.

Lists

In Elixir Lists looks 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.

Keywords List

Keywords List 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 like: [one: 1, three: 3]

In order to retrieve a item from a keyword list you can either use

Keyword.get([{:one, 1}, 2, {:three, 3}], :one) or use the shortcut [{:one, 1}, 2, {:three, 3}][:one]

Because keywords 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 are an efficient collection of key/value pairs. The key can have any value you want as a key usually the same type though. 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 a associative array. Here's how you can write a Map:

%{ :one => 1, :two => 2, 3 => 3, "four" => 4, [] => %{}, {} => [k: :v]}

Conclusion

Elixir is awesome, it's easy to understand has simple but powerful types and very useful tooling around it which will help you when starting to learn the Elixir.

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