Skip to content

Instantly share code, notes, and snippets.

@bobfirestone
Created March 20, 2017 21:35
Show Gist options
  • Save bobfirestone/02fb445478654aa4d20c3d741bed23af to your computer and use it in GitHub Desktop.
Save bobfirestone/02fb445478654aa4d20c3d741bed23af to your computer and use it in GitHub Desktop.
My code for week 2 section 9 of FUNCTIONAL PROGRAMMING IN ERLANG THE UNIVERSITY OF KENT
-module (two_nine).
-export ([double/1,evens/1,median/1,modes/1]).
double([H]) -> [H * 2];
double([H|T]) ->
[H * 2 | double(T)].
evens([H]) when 0 == H rem(2) -> [H];
evens([H|T]) ->
case H of
H when 0 == H rem(2) ->
[H|evens(T)];
_ ->
evens(T)
end.
median(List) ->
% lists:sort(List) comes from the standard library
median(lists:sort(List),length(List)).
median(List,Length) when 0 == Length rem(2) ->
Split = Length div(2),
(lists:nth(Split,List) + lists:nth(Split + 1,List))/2;
median(List,Length) ->
lists:nth(Length div(2) + 1,List).
modes([H]) -> H;
modes(List) -> modes(lists:sort(List),1).
modes([H|T],Count) ->
modes(T, H, Count, []).
modes([H],Last,Count,Accumulator) when H == Last ->
display_mode(mode_accumulator(Accumulator,{Last,Count + 1}));
modes([_H],Last,Count,Accumulator) when Count > 1 ->
display_mode(mode_accumulator(Accumulator,{Last,Count}));
modes([_H],_Last,_Count,Accumulator) ->
display_mode(Accumulator);
modes([H|T],Last,Count,Accumulator) when H == Last ->
modes(T,H,Count + 1, Accumulator);
modes([H|T],Last,Count,Accumulator) when Count > 1 ->
modes(T,H,1, mode_accumulator(Accumulator,{Last,Count}));
modes([H|T],_Last,Count,Accumulator) ->
modes(T,H,1, Accumulator).
mode_accumulator([],New) ->
[New];
mode_accumulator([{_H,Hc}|_T]=Original,{_N,Nc}=New) ->
case Original of
Original when Hc > Nc ->
Original;
Original when Hc < Nc ->
[New];
_ ->
lists:append(Original,New)
end.
display_mode([{N,_Nc}]) ->
N;
display_mode({N,_Nc}) ->
N;
display_mode([{N,_Nc}|T]) ->
[N, display_mode(T)].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment