Created
June 28, 2015 01:04
-
-
Save toraritte/5504ba16c1052a7f9aa1 to your computer and use it in GitHub Desktop.
count_chars example from Programming Erlang 2nd ed that works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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