I'm running into a problem when writing some simple erlang code for an old Advent of Code task.
The following program is supposed to read lines, group characters in a string by occurrence and then count the number of lines that have a repeat of three characters.
count_occurrences([], Map) -> Map;
count_occurrences([H | T], Map) ->
count_occurrences(T, maps:put(H, maps:get(H, Map, 0) + 1, Map)).
count(Line, Count) ->
Map = count_occurrences(Line, #{}),
case lists:member(3, maps:values(Map)) of
true -> Count + 1;
false -> Count
end.
run() ->
{ok, Binary} = file:read_file("data.txt"),
Lines = binary:split(Binary, <<"\n">>, [global]),
Result = lists:foldl(fun count/2, 0, Lines),
Result.
However, I get this error message:
10> c(day2).
{ok,day2}
11> day2:run().
** exception error: no function clause matching day2:count_occurrences(<<"bpacnmelhhzpygfsjoxtvkwuor">>,#{}) (day2.erl, line 5)
in function day2:count/2 (day2.erl, line 10)
in call from lists:foldl/3 (lists.erl, line 1263)
I don't understand why <<"bpacnmelhhzpygfsjoxtvkwuor">>,#{}
doesn't match the second "count_occurrences" function clause - a string is the same as a list, right? Why doesn't it match [H | T]?
3条答案
按热度按时间qij5mzcb1#
看看这个例子:
在 shell 中:
以及:
字符串和列表是一样的,对吧
是的,双引号字符串是创建整数列表的快捷方式,其中列表中的整数是字符的ascii代码。因此,上面的第二个函数子句永远不会匹配:
a. erl:6:警告:此子句不能匹配,因为第4行的前一个子句始终匹配
但是......二进制,比如
<<"abc">>
不是字符串,因此二进制不是创建整数列表的快捷方式。好吧,你知道的。但是,现在:
最后:
最后一个例子表明,在二进制文件中指定双引号字符串只是在二进制文件中指定逗号分隔的整数列表的一种快捷方式--然而,在二进制文件中指定双引号字符串并不会以某种方式将二进制文件转换为列表。
wlzqhblo2#
请注意,您也可以使用稍微不同的语法来逐一查看二进制档:
默认情况下,
H
假定为字节,但您可以添加修饰符以指定要选择的位数等。有关位语法,请参阅文档。h4cxqtbf3#
出现此错误的原因是函数
count_occurrences/2
的第一个参数应为list
-[<<"bpacnmelhhzpygfsjoxtvkwuor">>]
或"bpacnmelhhzpygfsjoxtvkwuor"
,但实际上是binary
-<<"bpacnmelhhzpygfsjoxtvkwuor">>
。请仔细检查第10行模块day2.erl
的函数count/2
中的输入数据Line
: