Created
May 14, 2020 23:40
-
-
Save fjpse/8963278c380936c44b09fd0ca76b6d9b 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(lst). | |
-export([sum/1, product/1, maximum/1, double/1, events/1, median/1, modes/1]). | |
%% | |
%% sum | |
%% | |
sum([]) -> 0; | |
sum([X|XS]) -> X + sum(XS). | |
%% | |
%% product | |
%% | |
product([]) -> 1; | |
product([H|TL]) -> H * product(TL). | |
%% | |
%% maximum | |
%% | |
maximum([X]) -> X; | |
maximum([H|TL]) -> max(H, maximum(TL)). | |
%% | |
%% double | |
%% | |
double([]) -> []; | |
double([H|TL]) -> [H*2 | double(TL)]. | |
%% | |
%% events | |
%% | |
events([]) -> []; | |
events([H|TL]) when H rem 2 == 0 -> | |
[H | events(TL)]; | |
events([_H|TL]) -> | |
events(TL). | |
%% | |
%% median | |
%% | |
median([_|_]=L) -> | |
median(lists:sort(L), length(L)). | |
median(X, L) when L rem 2 == 0 -> | |
sum(lists:sublist(X, L div 2, 2)) / 2; | |
median(X, L) -> | |
lists:nth(L div 2 + 1, X). | |
%% | |
%% modes | |
%% | |
modes([_|_]=L) -> | |
A = ocurrencies(L), | |
B = lists:reverse(lists:keysort(2, A)), | |
keys(B). | |
%% | |
%% ocurrencies(L) | |
%% | |
%% transform a list of numbers into a list of tuples {X,C} where | |
%% X -> one element of the list | |
%% C -> number of times that X appears into the list. | |
%% | |
%% The list is ordered to count items easier: [a,a,b,c,c,d,d,d] -> [{a,2}, {b,1}, {c,2}, {d,3}] | |
%% | |
ocurrencies(A) -> occurrencies(lists:sort(A), 0, []). | |
occurrencies([X], C, TL) -> | |
TL ++ [{X,C+1}]; | |
occurrencies([X,X|Xs], C, TL) -> | |
occurrencies([X|Xs], C+1, TL); | |
occurrencies([X,Y|Xs], C, TL) -> | |
occurrencies([Y|Xs], 0, TL ++ [{X, C+1}]). | |
%% | |
%% keys(L) | |
%% | |
%% transform a list of tuples {X,C} into a list of X. | |
%% | |
%% [{a,2}, {b,1}, {c,2}, {d,3}] -> [a, b, c, d] | |
%% | |
keys([]) -> []; | |
keys([{X,_C}|Xs]) -> [X | keys(Xs)]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment