The code is below:
-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.
when compiling the code in the Erlang shell, it reported the following errors:
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
I'm new in Erlang, and just can't find anything wrong by myself. How to correct it?
I guess you are using R17 since this feature is available only from this version.
looking at some doc, my understanding is that you should write the code that way (I can't test it, I am still using R15 :o)
The answers from IRC (#erlang@freenode):
H
is matched 2 times; or once and used to match N then. (This issue also appears with binaries)This should be solved in the coming releases.
As of release 17 this works:
Here is another version (only tested on 18) that is slightly more similar to the one in the book:
Quoted from OTP 17.0 Release Notes:
Currently you can use
maps
module to implementcount_characters
:Problem in match syntax.
Fof match use
:=
. Exampletest(#{ key := Test }) -> Test.
And for associated key and value use
=>
. Example:M = #{ keynew => 123 }
When you want to match a map, you need like this:
you can read the ducoment: http://joearms.github.io/2014/02/01/big-changes-to-erlang.html
@EWit, Felipe Mafra:
maps does just what it is supposed to do; what's missing here is the reduce part: