Given a function:
min(A, B) when A =< B -> A;
min(_A, B) -> B.
can I use this in the function foldl
in 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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With