Elixir notes Appendix – IEx

Background art by Dmitry Burmak

When you start to use Elixir, one of the first thing that you use or see people using is IEx, let’s understand its main features and how it can help you.

IEx which stands for Interactive Elixir it’s a core part of Elixir, it can be seen as Elixir’s REPL(Read–eval–print loop) if you’re coming for other modern languages. It’s helpful when you’re developing your application, and know how to use it can save you time.

Evaluating Expressions

IEx already comes with Elixir, so, if you have elixir installed (Or inside a docker container please) you just need to type iex and you’ll enter.

Erlang/OTP 22 [erts-10.4.1] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [hipe]              

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

At interactive mode any Elixir expression will be evaluated, for example:

iex(1)> 1 + 1
2

It sounds like ship ice to Antarctica for people coming from scripting languages with built-in REPL like Ruby or Python, but it’s worth knowing how to use IEx to be a powerful tool in your development.

It’s important to remember that any expression in IEx will be evaluated and not compiled, so, it’s not recommended to run benchmarks (or something like that) inside IEx.

Different from many similar applications IEx can’t be closed by typing ctrl + d or sending SIGINT signal (ctrl + c), if you type ctrl+c an interesting menu will be displayed:

iex(2)>
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution

For now, everything that you need to know is that if you type a and press enter you’ll close IEx, but one great people make a nice shortcut: Press ctrl+c two times and you’ll close it too.

Multi Line

It suports multi line expressions too:

iex(1)> fn (a, b) ->
...(1)> a + b
...(1)> end
#Function<13.91303403/2 in :erl_eval.expr/5>

If you want to copy and paste a multi line valid expression:

[1, [2], 3]
|> List.flatten()

Sometimes it won’t work, for example:

iex(1)> [1, [2], 3]
[1, [2], 3]
iex(2)> |> List.flatten()
** (SyntaxError) iex:2: syntax error before: '|>'

In these cases a nice tip is to place your multi line expression inside parentheses.

iex(2)> (
...(2)> [1, [2], 3]
...(2)> |> List.flatten()
...(2)> )
[1, 2, 3]

If you get stuck into a multi-line statement and doesn’t know how to get out of this, is just type #iex:break:

iex(3)> ["12
...(3)> c"
...(3)> 3 + 3
...(3)> 2 / 3
...(3)> \
...(3)> "
...(3)> ]
...(3)>
...(3)>
...(3)>
...(3)> #iex:break
** (TokenMissingError) iex:3: incomplete expression

Autocomplete

IEx comes with autocomplete too, and it works very fast, just type tab and it will show your options.

iex(1)> List.
Chars                 ascii_printable?/1    ascii_printable?/2
delete/2              delete_at/2           duplicate/2
first/1               flatten/1             flatten/2
foldl/3               foldr/3               improper?/1
insert_at/3           keydelete/3           keyfind/3
keyfind/4             keymember?/3          keyreplace/4
keysort/2             keystore/4            keytake/3
last/1                myers_difference/2    myers_difference/3
pop_at/2              pop_at/3              replace_at/3
starts_with?/2        to_atom/1             to_charlist/1
to_existing_atom/1    to_float/1            to_integer/1
to_integer/2          to_string/1           to_tuple/1
update_at/3           wrap/1                zip/1

iex(1)> List.

And if you type List.del it will complete for you offcourse, just press tab like you do on Linux.

Compiling

If you write a module:

defmodule Hello do
  def hello do
    IO.puts "Hello World"
  end
end

You can compile it inside your IEx, and then, use it.

iex(1)> c "test.ex"
[Hello]
iex(2)> Hello.hello
Hello World
:ok

Now if you change your module message to be “Hello Universe”, it won’t reload your module automatically, you need to recompile it using r/1 or compiling it again with c/1:

iex(4)> r Hello
warning: redefining module Hello (current version defined in memory)
  test.ex:1

{:reloaded, Hello, [Hello]}
iex(5)> Hello.hello
Hello Universe
:ok

A important thing to know is that if your file its a interpreted file of type exs, it will not be compiled and just interpreted.

Getting Past Expressions

It’s common to have a way to get the value of the past expressions, IEx you just need to use v:

iex(8)> 3 + 3
6
iex(9)> v
6

Shell history and history search

I love to use terminals, and I love to search throughout the history for a command that I made last year just typing Ctrl + r, inside IEx it’s possible to do the same just typing Ctrl + r too:

iex(1)> 1 + 2
3
iex(2)> 11 + 3
14
iex(3)> 1 + 3
4
(search)`11': 11 + 3

IEx doesn’t preserve your shell history if you close your session, but you can keep it by just setting one env var, can you imagine doing history search across all command that you ever typed?

export ERL_AFLAGS="-kernel shell_history enabled"

If you want to configure something about IEx, you can use configure/1, it has a lot of options of customization like colors, and you can setup things like history size too, I recommend you read about it here.

Debugging

One of the most loved thing to any developer it’s a debugger, with debugger you can develop more easily, find bugs and much more. Elixir happily has its debugger too, and to use it’s very simple, just paste require IEx; IEx.pry where you want that your application stop, let’s see an example with our Hello module, to see it working let’s add our message to one variable:

defmodule Hello do
  def hello do
    message = "Hello World"
    require IEx; IEx.pry
    IO.puts message
  end
end

After this, just call hello method inside our iex:

iex(1)> c "test.ex"
[Hello]
iex(2)> Hello.hello
Break reached: Hello.hello/0 (test.ex:4)

    2:   def hello do
    3:     message = "Hello World"
    4:     require IEx; IEx.pry
    5:     IO.puts message
    6:   end

pry(1)> message
"Hello World"
pry(2)> continue
Hello World
:ok

Elixir has many ways to debug your applications, this one is the simplest along with IO.inspect, and can be very helpful when you’re starting to study Elixir or dealing with simple bugs inside your app.

Displaying Help and Information

If you want to read docs about some module you just need to use helper h/1, it will display all the documentation shipped with the module like h Map, you can use the same helper to know about one method, for example h Map.keys (I’ll not paste here the output because its too long).

If you want to get information about any Elixir term, just use the i/1, example:

iex(7)> i Map
Term
  Map
Data type
  Atom

... ... 

You can get information about types defined inside module to:

iex(1)> t(Enum)
@type default() :: any()

@type index() :: integer()

@type element() :: any()

@type acc() :: any()

@type t() :: Enumerable.t()

Conclusions

IEx can help you when studying or developing Elixir, it has many beautiful features, in this post I don’t cover everyone but the principal ones, I think that all you need to start developing Elixir is here. In future posts I can return to IEx to talk about otherr features like connecting in remote nodes.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares@gmail.com), pm me on my Twitter or comment on this post!

Follow my blog to get notified every new post:

Newsletter 3 – 06/2020

Featured

The Practical Effects of the GVL on Scaling in Ruby – Have you ever wondered how VM-Locks affects your production system? This post talks about ruby GVL but its worth reading for anyone that have in production applications written in languages which have its owns locks (Python and Javascript for example). This post is fantastic, it starts with a brief view about concurrent execution and parallelism, diving deep into how Ruby GVL works under the hood, and finally explains how it affects your application performance. Worth reading.

Teleforking a process onto a different computer! – A great blog post talking about how this guy made what he calls telefork(), its like fork() but you fork your processes into a different machine, it’s completely insane, check it out.

Optimising for Concurrency: Comparing and contrasting the BEAM and JVM virtual machines – This post can be considered a little bit biased but it’s excellent it make a nice comparison between BEAM VM and JVM, and it’s nice features, without going deep.

Three bugs in the Go MySQL Driver – Large post about how GitHub team found three bugs in Go MySQL Driver and how they solve it. Warning: Dense post.

My journey optimizing the Go Compiler – I always love post of people describing how they contributed to a open source project, when this occurs with something that I love (Programming Languages) is even more fantastic.

What Is COBOL, and Why Do So Many Institutions Rely on It? – Want to know why COBOL is so important? It’s still already used a lot, this excellent and short post talk a little about it.

Ask HN: Dear open source devs how do you sustain yourself – A nice question on HN, a lot of open source devs talking about how they sustein themselves.

Tech

History / Fun

Erlang: The Movie – I never post videos here, but this one deserves. This is a video for those who like history, it’s a video of the engineering team at Ericson presenting Erlang to the world, it’s a short video worth watching if you like to learn about the past.

Interview

Rob Pike interview – A fascinating interview with Rob Pike about Go lang and opinions.

Other tech-related posts

Kubernetes Liveness and Readiness Probes: How to Avoid Shooting Yourself in the Foot – A nice post describing the difference between readiness and liveness probe in K8s. If you work with k8s you should know what is. This post also have an excellent part two that you can check here.

The Best Medium-Hard Data Analyst SQL Interview Questions – A great source to study advanced SQL, this document contains a lot of difficult SQL interview questions.

Advanced SQL and database books and resources – If you know the basics/intermediate of SQL probably you want to get better and better, this post shows you nice resources of advanced SQL.

JVM struggles and the BEAM – A nice post describing how BEAM VM helped him to find a bottleneck problem, while de JVM can’t do that. The post also contains a lot of good Elixir resources if you’re interested in start using it.

Finding secrets by decompiling Python bytecode in public repositories – Do you know why you need to put .pyc files in your .gitignore? This post explains it.

Debugging Go Applications using Delve – When I started to program Go, I had difficulties trying to debug Go programs, this tutorial can be very helpful for programmers who use fmt.println() to debug.

A re-introduction to Kubernetes – A simple but useful introduction to the main concepts behind k8s.

The last decade of programming – A brief analyze of the last decade of programming according to Google Trends.

Developing with Elixir/OTP Course Review – A review of pragprog studios’ Elixir video course, it looks great, I’m planning to buy it.

What Netlify’s Infrastructure Team Learned as It Increased Deploy Speed by up to 2x – This excellent post describes how Netlify improve his deploy speed by up to 2x, its very interesting to know how deploy works in this cloud providers.

Concurrency vs Parallelism and the Erlang Advantage – Do you know the difference between concurrency and parallelism? Thist post explains it with burritos! And as bonus it talks a bit about how Erlang handles it.

Rebuilding our tech stack for the new Facebook.com – Facebook has changed it design, this post describes what changed, the new stack and more.

What the heck happened with .org?.org domain registry was practically bought. This post talks about how it occurred and as bonus offers a great explanation about domain registry.

Elixir: Time for Some Configuration – Elixir has build time, startup time and runtime, it can be a problem if you don’t know how to use each one, specially with envs. Le’ts understand it.

An introduction to RabbitMQ – What is RabbitMQ? – A short and simple introduction to RabbitMQ.

The HTTP headers you don’t expect – A fun and short post! Let’s enjoy it.

10 most common mistakes using kubernetes – A great resource, I had already worked with k8s and some mistakes described there is very common. If you work with k8s or aims to, I recommend read it.

Network-Layer DDoS Attack Trends for Q1 2020 – Q1 Cloudflare DDOs report

Using Kotlin for Back-end Development: A Quick Overview – Kotlin is a JVM-based modern object-oriented language, its famous by its use in android development, but its worth on back-end too, let’s understand it better?

People

I’m a Latinx startup founder, and this is what I learned about making a company truly inclusive – A reflexive post from Drift co-founder about company truly inclusive.

Managers Playbook – A nice playbook for managers, it has a lot of heuristics and principles to effective management, it’s not a very long post or reading, but a lot of key small points. Worth reading even if you don’t want to be a manager.

Releases

Redis 6 is out! – Redis 6 is a big release in one of our favorites databases, a lot of new feature and improvements, is worth read what changed.

What’s coming in Go 1.15 – New major version of Go is coming, new linker, smaller binaries, let’s see whats new.