Skip to content

Instantly share code, notes, and snippets.

@ngnguyen1
Last active June 20, 2016 18:01
Show Gist options
  • Save ngnguyen1/4300db8f2c5558d7b9eb574f360c0d89 to your computer and use it in GitHub Desktop.
Save ngnguyen1/4300db8f2c5558d7b9eb574f360c0d89 to your computer and use it in GitHub Desktop.
%% This is the functions used to find min, max number and to calculate sum of a list without use fold.
%% find the maximum number of the list
max([H|T]) -> max2(T, H).
max2([], Max) -> Max;
max2([H|T], Max) when H > Max -> max2(T, H);
max2([_|T], Max) -> max2(T, Max).
%% find the minium number of the list
min([H|T]) -> min2(T,H).
min2([], Min) -> Min;
min2([H|T], Min) when H < Min -> min2(T,H);
min([_|T], Min) -> min2(T, Min).
%% find the sum of the list. Tail recursion.
sum(L) -> sum(L,0).
sum([], Sum) -> Sum;
sum([H|T], Sum) -> sum(T, Sum+H).
%% =================================================
%% Use fold here.
fold(_, Start, []) -> Start.
fold(F, Start, [H|T]) -> fold(F, F(H, Start), T).
%% Base fold function, we can re-write the function to find min, max number or to calculate sum of a list.
min([H|T]) -> fold(fun(A, B) when A > B -> A; (_, B) -> B end, H, T).
max([H|T]) -> fold(fun(A, B) when A < B -> A; (_, B) -> B end, H, T).
sum(L) -> fold(fun(A, B) -> A + B end, 0, L).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment