4

Early in the morning playing with Erlang I got a curious result:

   -module(bucle01).

   -compile(export_all).

   for(N) when N >=0 ->

                lists:seq(1,N).


   for(L,N) when L =< N ->

                lists:seq(L,N);

   for(L,N) when L > N ->

                lists:reverse(for(N,L)).

When I run the program I see this:

> bucle01:for(1,10).

[1,2,3,4,5,6,7,8,9,10]

> bucle01:for(10,1).

[10,9,8,7,6,5,4,3,2,1]

>bucle01:for(7,10).

[7,8,9,10]

>bucle01:for(8,10).

"\b\t\n"                %% What's that !?!

>bucle01:for(10,8).

"\n\t\b"               %% After all  it has some logic !

Any "Kool-Aid" to "Don't drink too much" please ?

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
user1694815
  • 121
  • 5

1 Answers1

7

Strings in Erlang are just lists of ASCII numbers. The Erlang shell tries to determine, without metadata, if your list is a list of numbers or a string by looking for printable characters.

\b (backspace), \t (tab) and \n (newline) are all somewhat common ASCII characters and therefore the shell shows you the string instead of the numbers. The internal structure of the list is exactly the same, however.

This is also covered by the Erlang FAQ: Why do lists of numbers get printed incorrectly?
And here's a few ideas to prevent this magic: Can I disable printing lists of small integers as strings in Erlang shell?

Community
  • 1
  • 1
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175