Created
March 5, 2017 03:01
-
-
Save shakerlxxv/ccca0457ce953a62d029822175ea91f9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%============================================================================== | |
%% Univ. Kent Functional Programing with Erlang | |
%% Week 2: Part 6 - Defining function over lists | |
%% | |
%% Description: | |
%% | |
%% Author: Brian L. Shaver | |
%% Date : 2017-03-04 | |
%%============================================================================== | |
-module(ex2_6). | |
-include_lib("eunit/include/eunit.hrl"). | |
-export([product/1,maximum/1,productTR/1,maximumTR/1]). | |
%------------------------------------------------------------------------------- | |
% recursive product of list | |
% the product of [] is defined as 1, so that it is a suitable product | |
% for a basic recursive approach. | |
product([]) -> | |
1; | |
product([X|Xs]) -> | |
X * product(Xs). | |
product_test() -> | |
?assertEqual(1,product([])), | |
?assertEqual(0,product([0])), | |
?assertEqual(12,product([1,2,6,1])), | |
?assertEqual(30.0,product([2,10,1.5])). | |
% tail recursive approach to product of list | |
productTR(L) -> | |
productTR(L,1). | |
productTR([],P) -> | |
P; | |
productTR([X|Xs],P) -> | |
productTR(Xs,X*P). | |
productTR_test() -> | |
?assertEqual(1,productTR([])), | |
?assertEqual(0,productTR([0])), | |
?assertEqual(12,productTR([1,2,6,1])), | |
?assertEqual(30.0,productTR([2,10,1.5])). | |
%------------------------------------------------------------------------------- | |
% list maximum | |
maximum([X]) -> | |
X; | |
maximum([X|Xs]) -> | |
max(X,maximum(Xs)). | |
maximum_test() -> | |
?assertEqual(3,maximum([1,2,3])), | |
?assertEqual(9,maximum([9,2,1])), | |
?assertEqual(2,maximum([2])). | |
% tail recursive approach to maximum of a list | |
maximumTR(L) -> | |
maximumTR(L,1). | |
maximumTR([X],M) -> | |
max(X,M); | |
maximumTR([X|Xs],M) -> | |
maximumTR(Xs,max(X,M)). | |
maximumTR_test() -> | |
?assertEqual(3,maximumTR([1,2,3])), | |
?assertEqual(9,maximumTR([9,2,1])), | |
?assertEqual(2,maximumTR([2])). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment