Created
May 17, 2020 08:56
-
-
Save pppillai/0f0e4312966d0c59f12ca0c10579bac3 to your computer and use it in GitHub Desktop.
This file contains 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
-module(week215). | |
-export([maximum/1, product/1, test/0]). | |
-include_lib("eunit/include/eunit.hrl"). | |
% Combining list elements: the product of a list | |
% Using the template from the last session, define an Erlang function to give the product of a list of numbers. The product of an empty list is usually taken to be 1: why? | |
%% because List is either a term or/and an empty list | |
%% and zero * anything is zero. | |
product(L) -> | |
product(L, 1). | |
product([], Result) -> | |
Result; | |
product([X|Xs], Result) -> | |
product(Xs, Result * X). | |
product_direct([]) -> | |
1; | |
product_direct([X|Xs]) -> | |
X * product_direct(Xs). | |
maximum(L) -> | |
maximum_(L). | |
maximum_([]) -> | |
[]; | |
maximum_([X]) -> | |
X; | |
maximum_([X, Y | Zs]) -> | |
maximum([max(X, Y)|Zs]). | |
test() -> | |
?assert(maximum([]) == []), | |
?assert(maximum([1]) == 1), | |
?assert(maximum([1,2]) == 2), | |
?assert(product([]) == 1), | |
?assert(product([1,2]) == 2), | |
?assert(product_direct([]) == 1), | |
?assert(product_direct([1,2]) == 2). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment