Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: is it possible to write the minimum function as a list fold?

Given a function:

min(A, B)  when A =< B -> A;
min(_A, B)             -> B.

can I use this in the function foldlin a similar fashion to this:

lists:foldl(fun min/2, 0, [1,2,3,4,5,6,7,8,9,10])

I believe it is not possible, because I have to set an initial value that will be compared to the rest of the list, e. g. there is no identity function that I can think of. Am I right?

Syntax is written in Erlang, but should be readable for non Erlang programmers, too.

like image 721
Magnus Kronqvist Avatar asked Mar 02 '11 13:03

Magnus Kronqvist


1 Answers

min(List) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, undefined, List).

Using undefined as the initial state should do the trick. Returns undefined for an empty list, which is kind of nice as an API.

If you want it to crash on an empty list, use this function header instead:

min([Head|Rest]) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, Head, Rest).
like image 150
Adam Lindberg Avatar answered Oct 04 '22 20:10

Adam Lindberg