Skip to content

Instantly share code, notes, and snippets.

@miwee
Last active April 20, 2021 07:51
Show Gist options
  • Save miwee/aa35a68a79678620e125aeeb23da32c2 to your computer and use it in GitHub Desktop.
Save miwee/aa35a68a79678620e125aeeb23da32c2 to your computer and use it in GitHub Desktop.
Common Elixir Pitfalls
  • Only nil and false are considered false (falsy values), everything else is considered true (truthy values). The following may surprise those coming from C/Python
iex(1)> x = 0
0
iex(2)> if x do
...(2)>   "True condition matched"
...(2)> else
...(2)>   "False condition matched"
...(2)> end  
"True condition matched"
  • Normally Atoms start with :, but anything starting with an upper case is also an Atom. They are perfectly legal, when used as value and compiler will not generate any error. If by mistake False is used instead of false, there will be no compile error or runtime error. Just that it will not work as (wrongly) expected, because False is neither false nor nil, and hence will be considered truthy value.
iex(1)> x = False
False
iex(2)> if x do
...(2)>   "True condition matched"
...(2)> else
...(2)>   "False condition matched"
...(2)> end  
"True condition matched"
  • From the getting started page, keep in mind errors in guards do not leak but instead make the guard fail:
iex> hd(1)
** (ArgumentError) argument error
    :erlang.hd(1)
iex> case 1 do
...>   x when hd(x) -> "Won't match"
...>   x -> "Got #{x}"
...> end
"Got 1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment