Skip to content

Instantly share code, notes, and snippets.

@oscherler
Last active March 6, 2017 16:12
Show Gist options
  • Save oscherler/8fb1f8e46e59be1a2e5795c268e8a065 to your computer and use it in GitHub Desktop.
Save oscherler/8fb1f8e46e59be1a2e5795c268e8a065 to your computer and use it in GitHub Desktop.
-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