Skip to content

Instantly share code, notes, and snippets.

@andreburgaud
Created June 27, 2017 04:14
Show Gist options
  • Save andreburgaud/17edf37b362dbec9b05f6175f3ee9690 to your computer and use it in GitHub Desktop.
Save andreburgaud/17edf37b362dbec9b05f6175f3ee9690 to your computer and use it in GitHub Desktop.
FutureLearn - Functional Programming in Erlang 2.6 - Functions over lists
-module(product).
-export([all_tests/0,test_sum/0,test_prod/0,test_maximum/0,sum/1,sumT/1,prod/1,
prodT/1,maximum/1,maximumT/1]).
%% sum implementation with direct recursion (per the video)
sum([]) -> 0;
sum([X|Xs]) -> X + sum(Xs).
%% sum implementation with tail recursion (per the video)
sumT(Xs) -> sumT(Xs, 0).
sumT([],S) -> S;
sumT([X|Xs],S) -> sumT(Xs, X+S).
test_sum() ->
(sum([]) =:= 0) and
(sum([1,2,3]) =:= 6) and
(sumT([]) =:= 0) and
(sumT([1,2,3]) =:= 6).
%% The product of an empty list is 1 because 1 is the identity for
%% multiplication (multiplying any number by 1 gives the number itself).
%% From a pragmatic stand point, if it were 0, the product of a list would be 0.
%% prod implementation with direct recursion (feels most natural)
prod([]) -> 1;
prod([X|Xs]) -> X*prod(Xs).
%% prod implementation with tail recursion
prodT(Xs) -> prodT(Xs,1).
prodT([],P) -> P;
prodT([X|Xs],P) -> prodT(Xs,X*P).
test_prod() ->
(prod([]) =:= 1) and
(prod([1,2,3,4]) =:= 24) and
(prodT([]) =:= 1) and
(prodT([1,2,3,4]) =:= 24).
%% maximum implementation with direct recursion
maximum([X]) -> X;
maximum([X|Xs]) -> max(X, maximum(Xs)).
%% maximum implementation with tail recursion (feels most natural)
maximumT([X]) -> X;
maximumT([X,Y|Zs]) -> maximum([max(X,Y)|Zs]).
%% maximumT([1,2,3])
%% maximumT([max(1,2)|[3]])
%% maximumT([2|[3]])
%% maximumT([2,3])
%% maximumT([max(2,3)|[]])
%% maximumT([3])
%% 3
test_maximum() ->
(maximum([1,2,3,1000]) =:= 1000) and
(maximum([1]) =:= 1) and
(maximumT([1,2,3,1000]) =:= 1000) and
(maximumT([1]) =:= 1).
all_tests() ->
test_sum() and test_prod() and test_maximum().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment