Skip to content

Instantly share code, notes, and snippets.

@paucus
Created March 5, 2017 21:59
Show Gist options
  • Save paucus/24204ddde353afb3316a68c567dfdc5a to your computer and use it in GitHub Desktop.
Save paucus/24204ddde353afb3316a68c567dfdc5a to your computer and use it in GitHub Desktop.
assignment 2.9
% Marcelo Ruiz Camauër
% assignment 2.9
-module(a29).
-export([double/1,evens/1, median/1]).
-include_lib("eunit/include/eunit.hrl").
%Define an Erlang function double/1 to double the elements of a list of numbers
double([])->[];
double(L) -> [Value * 2 || Value <- L].
% recusive version:
% double([]) -> [];
% double([H|T]) -> [2*H] || double(T).
% Define a function evens/1 that extracts the even numbers from a list of integers.
evens([])->[];
evens(L)->[Value || Value <- L, Value rem 2 =:=0].
%the median of a list of numbers:
%this is the middle element when the list is ordered (if the list is of even length you should
%average the middle two)
% code written by Vasiliy Rotaru, nice code! did not have time to make my own...:
median([X]) -> X;
median([X, Y]) -> (X + Y) / 2;
median([_, _ | _] = Xs) ->
Min = lists:min(Xs),
Max = lists:max(Xs),
Fn = fun(X) -> (X /= Max) and (X /= Min) end,
NextXs = lists:filter(Fn, Xs),
median(NextXs).
%the modes of a list of numbers:
%this is a list consisting of the numbers that occur most frequently in the list;
%if there is is just one, this will be a list with one element only
% to do...
%%%%%%%%%%%%%%%% tests %%%%%%%%%%%%%%
% invoke with 'a29:tests().' or "eunit:test(a29)."
double_test_()->
[?_assert(double([-1,2,3])==[-2,4,6]),
?_assert(double([])==[])
].
evens_test_()->
[?_assert([2,4,6]==evens([-1,2,3,4,6])),
?_assert([]==evens([]))
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment