Erlang: is it possible to write a minimal function as a list?

For function:

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

Can I use this in a function foldlsimilar to this:

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

I believe this is not possible because I have to set an initial value that will be compared with the rest of the list, e. There is no identification function that I can think of. I'm right?

The syntax is written in Erlang, but it should also be available to non-Erlang programmers.

+5
source share
3 answers
1> List = [42,13,25,3,19,20].
[42,13,25,3,19,20]
2> lists:foldl(fun(X, Y) -> erlang:min(X,Y) end, hd(List), tl(List)).   
3

The program crashes on an empty list, the recommended “let it crash” approach, rather than defensive programming.

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

undefined, . undefined , API.

, , :

min([Head|Rest]) ->
    Min = fun(A,  B) when A < B -> A;
             (_A, B)            -> B end,
    lists:foldl(Min, Head, Rest).
+11

undefined , , . , min .

, . , , , undefined .

+2

All Articles