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].
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]
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).
精彩评论