PragTob

PragTob

Blog Post: 10 Elixir gotchas

Elixir is a great language, but some behavior can be unintuitive, confusing and in the worst case lead to bugs. So, I took a look at 10 Elixir gotchas explaining why they exist and how to avoid them!

Most Liked

sasajuric

sasajuric

Author of Elixir In Action

Another gotcha with module attributes is that each reference injects the value, which can increase disk & mem usage. For example:

defmodule Foo do
  @x Enum.to_list(1..1_000_000)

  def foo, do: @x
  def bar, do: @x
end

Here we inject two identical large lists in the code, and the resulting file is 6 MB.

In contrast, the following code:

defmodule Foo do
  def foo, do: x()
  def bar, do: x()

  defp x, do: unquote(Enum.to_list(1..1_000_000))
end

produces a 4 MB beam, because the list is injected into the compiled beam only once.

In addition, I consider the 2nd version more flexible, because the “constant” can be provided after the implementation, which I often find better than listing various constants at the top of the file.

It’s also worth mentioning that both versions produce constants, as in terms which are handled in a special way by the runtime. See here for details.

BartOtten

BartOtten

Great post.

One more: is_atom(nil) == true as nil is an atom. However, most people mean a defined atom and not ‘undefined’ nil.

dwark

dwark

I got caught off guard by:

 [1, 2, 3] -- [1, 2, 3] -- [1, 2, 3]
[1, 2, 3]

After checking, the docs spell it out neatly once I starting looking for an explanation
(-- is right-associative).

BartOtten

BartOtten

Got a new gotcha today

Elixir’s ++/2 operator (list concatenation) has a special clause: If the right-hand side is not a list, the operation returns that right-hand side value instead of raising an error.

Never knew about it. Did bite me. Type checker did not warn that the enumeration would possibly
raise an exception. :frowning:

iex(1)> [] ++ nil
nil
iex(2)> [] ++ :foo
:foo
iex(3)> [] ++ "bla"
"bla"

The source in erlang is clear. This is the comment on the nil as right-hand side:

if (is_nil(lhs)) {
        /* This is buggy but expected, `[] ++ 'not_a_list'` has always resulted
         * in 'not_a_list'. */
        return rhs;

Doubt I like the behavior, but alas…there it is.

josevalim

josevalim

Creator of Elixir

The term ordering is essential for data structures such as maps, sets, ordsets, orddict, and others. Dynamic languages have heterogeneous collections, which means you can have keys, lists, and sets with distinct data types. Some of these data structures are more efficiently implemented by having a total order. If Erlang/Elixir only allowed you to compare the same data types, those data structures would have to define their “total” ordering, and it would ultimately be inefficient, especially for composite data types (e.g. storing structs inside sets, such as a set of dates).

The main source of confusion is because Elixir comparison operators are structural, not semantic. But there are good reasons for those as well. The docs go in detail over this: Kernel — Elixir v1.17.0-dev

The mutability of module attributes shouldn’t be a concern, really. Defining modules in Elixir is mutable a whole. defmodule, def, attrs are all mutable operations that define a module, functions, etc as you execute them. This what allows you, for example, to programmatically define a function. But, as meta-programming, those abilities are only really there at compile-time by design.

Where Next?

Popular in Blog Posts Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
brainlid
You are storing some Phoenix LiveView state in the browser. You want to retrieve that saved state as early as possible to improve the use...
New
jordiee
https://medium.com/@jpiepkow/distributed-state-is-hard-5a0d384c2f3c
New
MarcinKasprowicz
What I genuinely value at my workplace is that I can easily explore new languages through internal mobility. Throughout my career within ...
#js
New
pillaiindu
Our very handsome and humble José Valim (@josevalim) just published Kubernetes and the Erlang VM: orchestration on the large and the sma...
New
AstonJ
Update: How to use the blogs section You can post in one of the Official Blog Posts threads (like this one), or, via Devtalk and a new t...
New
zacksiri
In December of 2023 we came to the realization that we needed to build our own image server. After hitting a few snags we decided that it...
New
mudasobwa
Wrote some rant on Business Process Driven Development with Finite Automata (and Finitomata library in particular.)
New
mssantosdev
Our take on how to build a frontend style guide with Phoenix Components, Atomic Design and plain CSS, with focus on reusability and code ...
New
SmartLogic
Season four of the Elixir Wizards podcast launches today! This season we’re focused on system and application architecture. We’ll be doin...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

We're in Beta

About us Mission Statement