Skip to content

Instantly share code, notes, and snippets.

@50kudos
Created February 22, 2017 11:57
Show Gist options
  • Save 50kudos/725f1696ae61bb543409060718f68839 to your computer and use it in GitHub Desktop.
Save 50kudos/725f1696ae61bb543409060718f68839 to your computer and use it in GitHub Desktop.
-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)).
@hgisinger
Copy link

hgisinger commented Feb 27, 2017

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)).

@7-fl
Copy link

7-fl commented Feb 28, 2017

@hsinger,

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