Last active
March 6, 2017 16:12
-
-
Save oscherler/8fb1f8e46e59be1a2e5795c268e8a065 to your computer and use it in GitHub Desktop.
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( occurences ). | |
-export( [ occurences/1 ] ). | |
filter( _F, [] ) -> | |
[]; | |
filter( F, [ X | Xs ] ) -> | |
case F( X ) of | |
true -> [ X | filter( F, Xs ) ]; | |
_ -> filter( F, Xs ) | |
end. | |
% counts the number of occurrences of each value in a list, and returns a list of tuples, | |
% one for each value, containing the value and its occurences. | |
% | |
% > occurences( [ 1, 2, 3, 2, 1 ] ) | |
% [{1,2},{2,2},{3,1}] | |
occurences( Xs ) -> | |
occurences( Xs, [] ). | |
occurences( [], R ) -> | |
R; | |
occurences( [ X | Xs ], R ) -> | |
Curr = filter( fun( Y ) -> | |
case Y of | |
{ X, _ } -> true; | |
_ -> false | |
end | |
end, R ), | |
New = case Curr of | |
[] -> { X, 1 }; | |
[ { X, N } ] -> { X, N + 1 } | |
end, | |
NoX = filter( fun( Y ) -> | |
case Y of | |
{ X, _ } -> false; | |
_ -> true | |
end | |
end, R ), | |
occurences( Xs, [ New | NoX ] ). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment