如何在列表中存储整数

How to store integers in a list

我正在尝试分隔一个整数数组以计算其中有多少个重复数字。

对于此输入 [10, 20, 20, 10, 10, 30, 50, 10, 20] 我收到以下输出:

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

问题

我想知道如何生成以下输出

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

我用来生成地图输出的函数是:


%% 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.

你的输出实际上是正确的。 \n 的 ascii 值为 10。erlang 中没有原生的 string 数据类型。字符串不是值列表。 erlang:is_list("abc") 会 return 正确。

尝试 [1010, 1020, 1020, 1010, 1010, 1030, 1050, 1010, 1020] 作为输入。它应该显示所有数字。

您可以使用shell:strings/1 function来处理数字显示为字符的问题。当调用 shell:strings(true) 时,数字将打印为字符:

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

调用 shell:strings(false) 将导致数字打印为数字:

3> shell:strings(false).
true
4> [10,10,10].
[10,10,10]

您还可以使用 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.