Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(list_utils).
- -export([double/1, evens/1, sort/1, list_at/2, median/1, count/2, mode/1]).
- % Transforming list elements
- % Define an Erlang function double/1 to double the elements of a list of numbers.
- double([]) -> [];
- double([X|Xs]) -> [2*X | double(Xs)].
- % Filtering lists
- % Define a function evens/1 that extracts the even numbers from a list of integers.
- evens([]) -> [];
- evens([X|Xs]) when X rem 2 == 0 ->[X | evens(Xs)];
- evens([X|Xs]) when X rem 2 > 0 -> evens(Xs).
- % Sort the list
- sort([]) -> [];
- sort([X]) -> [X];
- sort([X,Y]) when X =< Y -> [X,Y];
- sort([X,Y]) when X > Y -> [Y,X];
- sort(X) ->
- {X1, X2} = lists:split(length(X) div 2, X),
- lists:merge(sort(X1), sort(X2)).
- % Return the element at position Index
- list_at(X, Index) -> list_at(X, Index, 0).
- list_at([X|_], Index, Index) -> X;
- list_at([_|Xs], Index, CurrentIndex)
- when CurrentIndex < Index ->
- list_at(Xs, Index, CurrentIndex + 1).
- % Median
- median(X) ->
- XLength = length(X),
- MiddlePosition = XLength div 2,
- XSorted = sort(X),
- list_at(XSorted, MiddlePosition).
- % Count the number of occurrences of Item in X
- count(X, Item) -> count(X, Item, 0).
- count([], _, Acc) -> Acc;
- count([X|Xs], X, Acc) -> count(Xs, X, 1+Acc);
- count([_|Xs], Item, Acc) -> count(Xs, Item, Acc).
- % Mode
- mode(X) ->
- XUniq = sets:to_list(sets:from_list(X)),
- mode(XUniq, X, nil, -1).
- mode([], _XOccurrences, ItemMax, _Max) -> ItemMax;
- mode([X|Xs], XOccurrences, ItemMax, Max) ->
- XCount = count(XOccurrences, X),
- if
- XCount > Max -> mode(Xs, XOccurrences, X, XCount);
- XCount =< Max -> mode(Xs, XOccurrences, ItemMax, Max)
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement