ITChap
ITChap

Reputation: 4732

Map pattern matching in function head with variable

I wrote a simple function to get the number of occurrence of each character in a string:

count([], Result) ->
  Result;

count([Head|Tail], #{Head := Count} = Result) ->
  count(Tail, Result#{Head := Count +1});

count([Head|Tail], Result) ->
  count(Tail, Result#{Head => 1}).

But apparently something is wrong with the pattern matching of the map. I get variable 'Head' is unbound.From the doc it doesn't seem to be an illegal pattern and does work with variables or lists.

So, am I doing something wrong (if yes can you explain what/why) or is it something else that has not been implemented for the maps yet ?

Upvotes: 2

Views: 758

Answers (1)

Máté
Máté

Reputation: 2345

You can't use pattern matching like that on the map's key in the function head - take a look at this example, or this other answer.

However you can use the is_key/2 function to check if it is present.

Alternatively, you could use the default part of maps:get/3:

count([], Result) ->
  Result;

count([Head|Tail], Result) ->
  Count = maps:get(Head, Result, 0),
  count(Tail, Result#{Head => Count + 1}).

Or use update_with/4 with a setter function.

Upvotes: 3

Related Questions