Erlang, lists: find the item with the maximum defined by fun

The module listsprovides a function for finding the maximum list lists:max(List).

Is there a type function lists:maxfun(Fun, List)? This fun should be used for all elements, but maxfunshould return this element instead of a value. For instance:

Fun gets [X,Y] and calcs X+Y
lists:maxfun(Fun,[[1,1],[1,2]]} -> [1,2].
+3
source share
2 answers

You can use, for example, this trick:

1> F=fun([X,Y]) -> X+Y end.                                  
#Fun<erl_eval.6.13229925>
2> element(2, lists:max([ {F(X), X} || X <- [[1,1],[1,2]]])).
[1,2]
+4
source

You can use the lists: foldl for it, something like this:

lists:foldl(fun([X1,Y1],[X2,Y2]) when X1 + Y1 > X2 + Y2 ->
                [X1,Y1];
               (_, Acc) ->
                 Acc
            end, [0,0], ListOfLists).
+1
source

Source: https://habr.com/ru/post/1786974/


All Articles