Skip to content

Instantly share code, notes, and snippets.

@toraritte
Created June 28, 2015 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toraritte/5504ba16c1052a7f9aa1 to your computer and use it in GitHub Desktop.
Save toraritte/5504ba16c1052a7f9aa1 to your computer and use it in GitHub Desktop.
count_chars example from Programming Erlang 2nd ed that works
-module(count_chars).
-export([count_chars/1, count_characters/1]).
count_characters(Str) ->
count_characters(Str, #{}).
%% maps module functions cannot be used as guards (release 17)
%% or you'll get "illegal guard expression" error
count_characters([H|T], X) ->
case maps:get(H,X,no_key) of
no_key -> count_characters(T, maps:put(H,1,X));
Cnt -> count_characters(T, maps:update(H,Cnt+1,X))
end;
count_characters([], X) ->
X.
%% Only difference from count_characters/1 is that maps:is_key/2 is used
%% instad of maps:get/3
count_chars(L) -> c(L,#{}).
c([],M) -> M;
c([H|T],M) ->
case maps:is_key(H,M) of
% maps:put =>
% maps:update :=
true -> c(T, maps:update(H, maps:get(H,M)+1, M));
false -> c(T, maps:put(H, 1, M))
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment