Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Last active May 29, 2017 11:21
Show Gist options
  • Save hhimanshu/311232844dc3a4c764e3 to your computer and use it in GitHub Desktop.
Save hhimanshu/311232844dc3a4c764e3 to your computer and use it in GitHub Desktop.
Erlang: Find Minimum and Maximum in list
-module(recursive).
-export([minimum/1, maximum/1]).
minimum([]) -> io:format("can not find minimum of empty list~n");
minimum([H|T]) ->
minimum(H, T).
minimum(Min, [H|T]) ->
case Min < H of
true -> minimum(Min, T);
false -> minimum(H, T)
end;
minimum(Min, []) -> Min.
maximum([]) -> io:format("can not find max from empty list~n");
maximum([H|T]) ->
maximum(H, T).
maximum(Max, [H|T]) ->
case Max > H of
true -> maximum(Max, T);
false -> maximum(H, T)
end;
maximum(Max, []) -> Max.
@nootanghimire
Copy link

I'm new to Erlang, and wrote this function a bit in a different way, could you comment on which would be more erlang-y ?

-module(lists1).
-export([min/1, max/1]).


min([]) ->
    {error, empty_list};

min([H|T]) ->
    min1(H, T).

min1(M, [H|T]) when M < H ->
    min1(M, T);
min1(M, [H|T]) when M >= H ->
    min1(H, T);
min1(M, []) ->
    M.

max([]) ->
    {error, empty_list};

max([H|T]) ->
    max1(H, T).

max1(M, [H|T]) when M >= H ->
    max1(M, T);
max1(M, [H|T]) when M < H ->
    max1(H, [H|T]);
max1(M, []) ->
    M.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment