Unexpected output of very simple recursion method on a simple list

HelIo - I have created a simple recursion method while trying to learn elixir and am getting some unexpected output. Can anyone help me understand what the output changes to the special return characters instead of continuing the list output as I would expect?

Code:

defmodule Recurse do
  def loopy([head | tail]) do
    IO.puts "Head: #{head} Tail: #{inspect(tail)}"
    loopy(tail)
  end

  def loopy([]), do: IO.puts "Done!"

end

Recurse.loopy([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

The methods outputs as expected until the head is equal to 6, at which point the tail becomes a set of special characters not in a list anymore.

Output:

Head: 1 Tail: [2, 3, 4, 5, 6, 7, 8, 9, 10]
Head: 2 Tail: [3, 4, 5, 6, 7, 8, 9, 10]
Head: 3 Tail: [4, 5, 6, 7, 8, 9, 10]
Head: 4 Tail: [5, 6, 7, 8, 9, 10]
Head: 5 Tail: [6, 7, 8, 9, 10]
Head: 6 Tail: ‘\a\b\t\n’
Head: 7 Tail: ‘\b\t\n’
Head: 8 Tail: ‘\t\n’
Head: 9 Tail: ‘\n’
Head: 10 Tail:
Done!

Here is the information about my Erlang & Elixir environment:

$ elixir -v
Erlang/OTP 23 [erts-11.2.1] [source] [64-bit] [smp:16:16] [ds:16:16:10] [async-threads:1] [hipe]
Elixir 1.11.4 (compiled with Erlang/OTP 23)

This is a common point of confusion for new folks, you can read more about this here: Binaries, strings, and charlists - The Elixir programming language

4 Likes

Thank you, I did understand how strings were stored as binary and was trying to review that page, but I think the key piece that wasn’t clicking until reading it again after your posted it was that my list of integers were being interpreted as a Charlist.

Thank you for the direction.

Interpreting integers as code points may lead to some surprising behavior. For example, if you are storing a > list of integers that happen to range between 0 and 127, by default IEx will interpret this as a charlist and it
will display the corresponding ASCII characters.

1 Like