jtf
jtf

Reputation: 33

Erlang, lists: find element with maximum defined by a fun

The lists module provides a function to find the maximum of a list, lists:max(List).

Is there a function like lists:maxfun(Fun, List)? The given fun should be used for all Elements and maxfun should give this Element back instead of the value. For example:

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

Upvotes: 3

Views: 786

Answers (2)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26121

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]

Upvotes: 4

Lukas
Lukas

Reputation: 5327

You could use 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).

Upvotes: 1

Related Questions