Created
February 22, 2017 11:57
-
-
Save 50kudos/725f1696ae61bb543409060718f68839 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(w2list). | |
-export([t_product/1, product/1, t_maximum/1, maximum/1]). | |
% t_ prefix means tail recursion implementation. | |
t_product(L) -> | |
t_product(L, 1). | |
t_product([], P) -> | |
P; | |
t_product([H|T], A) when is_number(H) -> | |
t_product(T, H * A). | |
product([]) -> | |
1; | |
product([H|T]) when is_number(H) -> | |
H * product(T). | |
% No magic maximum value like an infinity | |
% Maximum of empty list is an empty list | |
% | |
t_maximum([]) -> | |
[]; | |
t_maximum(L) -> | |
t_maximum(L, hd(L)). | |
t_maximum([], M) -> | |
M; | |
t_maximum([_H|T], A) -> | |
case T of | |
[] -> A; | |
_ -> t_maximum(T, max(A, hd(T))) | |
end. | |
maximum([]) -> []; | |
maximum([A]) -> A; | |
maximum([H|T]) -> | |
max(H, maximum(T)). |
I like the way you used the first element of the list as the Max. I used 0, and now I realize my algorithm was wrong: if all the numbers in the list were negative, my starting value of 0 would end up being the result--which would be wrong. I need better tests!
7
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another version of t_maximum
t_maximum([]) -> [];
t_maximum([X | Xs]) -> t_maximum(Xs, X).
t_maximum([], Max) -> Max;
t_maximum([X | Xs], Max) -> t_maximum(Xs, max(Max, X)).