Notes on Elixir

I’m reading Programming Elixir 1.3 by Dave Thomas. I’ve compiled some notes on Elixir here for personal reference. Elixir is basically a Ruby-ish wrapper around Erlang, a language developed at Ericsson in the 1980’s. Erlang is known for being extremely reliable, and concurrent.

Installation

On a mac, this is pretty easy, just use brew:

$ brew install elixir

Running the Interpreter

Elixir provides an interpreter for debugging, and exploration.

$ iex
Erlang/OTP 21 [erts-10.0.4]  [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.7.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

The interpreter has a number of builtin helper functions. You can see these by typing h at the interpreter prompt. One helper in particular is i, which provides information about a value.

Compiling

We can compile and run code using the elixir utility.

Suppose we have a file called hello.exs

IO.puts "Hello, World!"

Then we can interpret a script from the command line by saying:

$ elixir hello.exs

Or we can run this from the interpreter:

$ iex
iex> c "hello.exs"

The convention is that scripts tend to have a “.exs” extension, while standalone applications have an “.ex” extension.

Pattern Matching

Elixir doesn’t use an equal sign for assignment, but rather for assertion. Probably the best way to think of it is the way an equal sign is used in algebra.

Configure Sublime3

Install this for syntax highlighting, snippets, and keybindings. On a mac, do this:

$ cd ~/Library/Application\ Support/Sublime\ Text\ 3/Packages
$ git clone git://github.com/elixir-lang/elixir-tmbundle Elixir

Install this for code completion.

Setup a Project

Elixir uses the mix build tool to create new projects, manage dependencies, run tests, and run code. Start by saying,

$ mix new <project>

Erlang projects typically use rebar3 as a build tool.

Testing

In a mix project, run all tests by saying:

$ mix test

Run a specific test by providing a path to that test.

Finding Packages

Elixir uses hex to find packages. In order to use a package in mix, add that package to the deps function in the mix.exs file in the root of your project directory.

  ...
  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
      {:httpoison, "~> 1.2"},
    ]
  end
  ...

Then run,

$ mix deps.get
$ mix deps

Load Mix into Iex

You can load your mix environment into iex by saying,

$ iex -S mix

Actors

Actors are like threads, or very light native OS processes, that run on the Erlang VM. In functional programming, these are used instead of objects in object oriented programming.