Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.67 KB | None | 0 0
  1. -module(list_utils).
  2. -export([double/1, evens/1, sort/1, list_at/2, median/1, count/2, mode/1]).
  3.  
  4. % Transforming list elements
  5. % Define an Erlang function double/1 to double the elements of a list of numbers.
  6. double([]) -> [];
  7. double([X|Xs]) -> [2*X | double(Xs)].
  8.  
  9. % Filtering lists
  10. % Define a function evens/1 that extracts the even numbers from a list of integers.
  11. evens([]) -> [];
  12. evens([X|Xs]) when X rem 2 == 0 ->[Xevens(Xs)];
  13. evens([X|Xs]) when X rem 2 > 0 -> evens(Xs).
  14.  
  15. % Sort the list
  16. sort([]) -> [];
  17. sort([X]) -> [X];
  18. sort([X,Y]) when X =< Y -> [X,Y];
  19. sort([X,Y]) when X > Y -> [Y,X];
  20. sort(X) ->
  21.     {X1, X2} = lists:split(length(X) div 2, X),
  22.     lists:merge(sort(X1), sort(X2)).
  23.  
  24. % Return the element at position Index
  25. list_at(X, Index) -> list_at(X, Index, 0).
  26. list_at([X|_], Index, Index) -> X;
  27. list_at([_|Xs], Index, CurrentIndex)
  28.     when CurrentIndex < Index ->
  29.             list_at(Xs, Index, CurrentIndex + 1).
  30.  
  31. % Median
  32. median(X) ->
  33.     XLength = length(X),
  34.     MiddlePosition = XLength div 2,
  35.     XSorted = sort(X),
  36.     list_at(XSorted, MiddlePosition).
  37.  
  38. % Count the number of occurrences of Item in X
  39. count(X, Item) -> count(X, Item, 0).
  40. count([], _, Acc) -> Acc;
  41. count([X|Xs], X, Acc) -> count(Xs, X, 1+Acc);
  42. count([_|Xs], Item, Acc) -> count(Xs, Item, Acc).
  43.  
  44. % Mode
  45. mode(X) ->
  46.     XUniq = sets:to_list(sets:from_list(X)),
  47.     mode(XUniq, X, nil, -1).
  48.  
  49. mode([], _XOccurrences, ItemMax, _Max) -> ItemMax;
  50. mode([X|Xs], XOccurrences, ItemMax, Max) ->
  51.     XCount = count(XOccurrences, X),
  52.     if
  53.         XCount > Max -> mode(Xs, XOccurrences, X, XCount);
  54.         XCount =< Max -> mode(Xs, XOccurrences, ItemMax, Max)
  55.     end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement