3

Can someone explain this unexpected list comprehension strangeness from Erlang?

4> [A+B || [A, B] <- [1, 2, 3, [5, 6]]].
"\v"

Expected: 11

Got: "\v"

What must be done to get the expected output?

2240
  • 1,547
  • 2
  • 12
  • 30
Muhammad Lukman Low
  • 8,177
  • 11
  • 44
  • 54
  • You can use `shell:strings(false)` but keep in mind that this option is global. [Can I disable printing lists of small integers as strings in Erlang shell?](https://stackoverflow.com/questions/2348087/can-i-disable-printing-lists-of-small-integers-as-strings-in-erlang-shell) –  Mar 10 '18 at 08:51
  • See also [this question](https://stackoverflow.com/q/7371955/113848) and [this question](https://stackoverflow.com/q/20792966/113848). – legoscia Mar 10 '18 at 12:49

1 Answers1

6

According to the Erlang documentation:

A string is a list of codepoints, binaries with UTF-8-encoded codepoints (UTF-8 binaries), or a mix of the two.

"abcd"               % is a valid string  
<<"abcd">>           % is a valid string  
["abcd"]             % is a valid string  
<<"abc..åäö"/utf8>>  % is a valid string  
<<"abc..åäö">>       % is NOT a valid string,  
                     % but a binary with Latin-1-encoded codepoints  
[<<"abc">>, "..åäö"] % is a valid string  
[atom]               % is NOT a valid string

So in above you got integer 11 inside a list or [11]:

Eshell V8.3  (abort with ^G)
1> [A+B || [A, B] <- [1, 2, 3, [5, 6]]].
"\v"
%% With hd/1 function you can get first element (head) of a list
2> hd([A+B || [A, B] <- [1, 2, 3, [5, 6]]]).
11
3> [11].
"\v"

Erlang VM prints a printable list in form of string. Currently it supports two printable range. latin1 which is default and unicode.

$ erl
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V8.3  (abort with ^G)
1> io:printable_range().
latin1

You can change latin1 to unicode using +pc flag:

$ erl
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V8.3  (abort with ^G)
1> [1662]. %% not printable in latin1 range
[1662]
2> 
BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded
       (v)ersion (k)ill (D)b-tables (d)istribution
a
$ erl +pc unicode
Erlang/OTP 19 [erts-8.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V8.3  (abort with ^G)
1> [1662].
"پ"
2>
Pouriya
  • 1,626
  • 11
  • 19