Created
May 8, 2020 05:43
-
-
Save gorkaio/8671e50a13b59e5c5d4f659d97dd9723 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(list_functions). | |
-export([product/1,maximum/1,product_notail/1,maximum_notail/1]). | |
-export([product_test/0,maximum_test/0,product_notail_test/0,maximum_notail_test/0]). | |
%% Product %%% | |
product([]) -> 1; | |
product([A|B]) -> product([A|B], 1). | |
product([], P) -> P; | |
product([A|B], P) -> product(B, A*P). | |
product_test() -> | |
1 = product([]), | |
2 = product([2]), | |
6 = product([2,3]), | |
42 = product([2,7,3,1]), | |
-2 = product([2,-1]), | |
0 = product([3,7,0,21]), | |
passed. | |
%% Maximum %%% | |
maximum([A|[]]) -> A; | |
maximum([A|B]) -> maximum(B,A). | |
maximum([], Max) -> Max; | |
maximum([A|L], Max) -> | |
maximum(L, max(A, Max)). | |
maximum_test() -> | |
7 = maximum([7]), | |
1 = maximum([0, 1]), | |
7 = maximum([5, 3, 7]), | |
-2 = maximum([-7, -3, -2]), | |
passed. | |
%% Product non tail-recursive %%% | |
product_notail([]) -> 1; | |
product_notail([A|[]]) -> A; | |
product_notail([A|[B|T]]) -> A*B*product(T). | |
product_notail_test() -> | |
1 = product_notail([]), | |
2 = product_notail([2]), | |
6 = product_notail([2,3]), | |
42 = product_notail([2,7,3,1]), | |
-2 = product_notail([2,-1]), | |
0 = product_notail([7,3,0,21]), | |
passed. | |
%% Maximum non tail-recursive %%% | |
maximum_notail([A|[]]) -> A; | |
maximum_notail([A,B]) -> max(A,B); | |
maximum_notail([A|B]) -> max(A, maximum(B)). | |
maximum_notail_test() -> | |
7 = maximum_notail([7]), | |
1 = maximum_notail([0, 1]), | |
7 = maximum_notail([5, 3, 7]), | |
-2 = maximum_notail([-7, -3, -2]), | |
passed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well done!