0

I'm trying to separate an array of integers to count how many repeated numbers are there.

For this input [10, 20, 20, 10, 10, 30, 50, 10, 20] I am receiving the following output:

#{10=>"\n\n\n\n",20=>[20,20],30=>[30],50=>"2"}

Question

I would like to know how can I generate the following output

#{10=>[10,10,10,10],20=>[20,20],30=>[30],50=>[50]}

The function I am using to generate the map output is:


%% Next: number
%% Acc: map
separate_socks(Next, Acc) ->
    KeyExists = maps:is_key(Next, Acc),

    case KeyExists of
        true ->
            CurrentKeyList = maps:get(Next, Acc),
            maps:update(Next, [Next | CurrentKeyList], Acc);
        false -> maps:put(Next, [Next], Acc)
    end.
Eric Douglas
  • 449
  • 7
  • 12

3 Answers3

1

Your output is actually correct. The ascii value for \n is 10. There is no native string data type in erlang. A string is nothing by a list of values. erlang:is_list("abc") would return true.

Try [1010, 1020, 1020, 1010, 1010, 1030, 1050, 1010, 1020] as input. It should display all numbers.

1

You can use the shell:strings/1 function to deal with the problem of numbers being displayed as characters. When shell:strings(true) is called, numbers will be printed as characters:

1> shell:strings(true).
true
2> [10,10,10].
"\n\n\n"

Calling shell:strings(false) will result in the numbers being printed as numbers instead:

3> shell:strings(false).
true
4> [10,10,10].
[10,10,10]
Steve Vinoski
  • 19,847
  • 3
  • 31
  • 46
1

You can also format the output with io:format():

1> M = #{10=>[10,10,10,10],20=>[20,20],30=>[30],50=>[50]}.
#{10 => "\n\n\n\n",20 => [20,20],30 => [30],50 => "2"}

2> io:format("~w~n", [M]).
#{10=>[10,10,10,10],20=>[20,20],30=>[30],50=>[50]}
ok

w

Writes data with the standard syntax. This is used to output Erlang terms.

7stud
  • 46,922
  • 14
  • 101
  • 127