How to do nil
safe concatenation of lists in Elixir?
I have presented few inline examples of the situation and response with ++
Looks like nil
is treated as a special entity when concatenating.
Why does this happen?
# Append two empty list ✅
iex(1)> [] ++ []
[]
# Append empty list to nil ❌
iex(2)> [] ++ nil
nil # Result should be []
# Append non empty list to nil ❌
iex(3)> [1] ++ nil
[1 | nil] # Result should be [1]
# Append non empty list to nil and enumerate ❌
iex(5)> a = [1, 2] ++ nil
[1, 2 | nil]
iex(6)> Enum.each(a, fn p -> IO.puts(p) end)
1
2
** (FunctionClauseError) no function clause matching in Enum."-each/2-lists^foreach/1-0-"/2
# Add more lists with nil ❌
iex(5)> [1, 2] ++ nil ++ []
** (ArgumentError) argument error