2

By mistake, I typed the following:

iex(1)> x = ["hello" | "world"]

I'm pretty surprised that it didn't fail and I can't quite understand what is the type of the result.

iex(2)> is_list(x)
true
iex(3)> length(x)
** (ArgumentError) argument error
    :erlang.length(["hello" | "world"])

The same happen for whatever type that follow the | symbol:

iex(4)> x = [1 | {}]
[1 | {}]
iex(5)> is_list(x)
true
iex(6)> length(x)
** (ArgumentError) argument error
    :erlang.length([1 | {}])

Notice, however, that pattern matching do work.

iex(7)> [head | tail] = ["hello" | "world"]
["hello" | "world"]
iex(8)> head
"hello"
iex(9)> tail
"world"
  1. Is this behaviour intended?
  2. If so, what for?
Nagasaki45
  • 2,634
  • 1
  • 22
  • 27
  • 3
    These are called `improper lists`. See http://stackoverflow.com/questions/5088575/practical-use-of-improper-lists-in-erlang-perhaps-all-functional-languages – CoderDennis May 27 '16 at 17:09
  • Thanks for the reference! there is even more info here: http://stackoverflow.com/q/1919097/1224456 – Nagasaki45 May 27 '16 at 18:51

0 Answers0