代码如下:
-module(map_demo).
-export([count_characters/1]).
count_characters(Str) ->
count_characters(Str, #{}).
count_characters([H|T], #{ H => N } = X) ->
count_characters(T, X#{ H := N+1 });
count_characters([H|T], X) ->
count_characters(T, X#{ H => 1});
count_characters([], X) ->
X.
在Erlang shell中编译代码时,它报告了以下错误:
1> c(map_demo).
map_demo.erl:7: illegal pattern
map_demo.erl:8: variable 'N' is unbound
map_demo.erl:10: illegal use of variable 'H' in map
map_demo.erl:7: Warning: variable 'H' is unused
error
我是Erlang的新手,我自己找不到任何错误。如何纠正它?
发布于 2014-04-17 10:44:43
当你想要匹配一个地图时,你需要这样:
#{key1 := Pattern1, key2 := Pattern2, ...} = VarContainingAMap.
您可以阅读该文档:https://joearms.github.io/published/2014-02-01-big-changes-to-erlang.html
发布于 2015-02-18 23:06:25
@EWit,Felipe Mafra:
maps做了它应该做的事情;这里缺少的是reduce部分:
count(Str) -> M = count_chars(Str, maps:new()), % maps part, bad naming
L = maps:to_list(M), % to be able to sum
N = [X || {_,X} <- L], % strip the numbers
lists:sum(N). % sum them up
count_chars([H|T], Map) when is_map(Map)->
N = maps:get(H, Map, 0),
count_chars(T, maps:put(H, N + 1, Map));
count_chars([], Map) -> Map.
发布于 2014-04-16 18:46:08
匹配语法中存在问题。
Fof匹配使用:=
。示例
test(#{ key := Test }) -> Test.
对于关联的键和值,请使用=>
。示例:M = #{ keynew => 123 }
https://stackoverflow.com/questions/23106543
复制相似问题