I need a function to find max element of a list according to some custom ordering function, assuming that the function implements a total order (elements being compared might not even be numbers). Unlike Sort
, the predefined Max
function does not accept a custom ordering function. A naïve solution would be to use Sort[list, p]〚1〛
, but this would unnecessarily sort the whole list, while I only need to find the first element.
I ended up defining
max[list_, p_] := list[[Ordering[list, 1, p][[1]] ]];
and it works fine from performance point of view. But I wonder if there is a more simple or natural way to do this task. Is there a predefined function solving this problem that I missed?
MaximalBy
is intended to do this. It is new in version 10. $\endgroup$MaximalBy
requires a mapping from elements of the list to some expressions that can be compared canonically. It's not always easy to construct such a mapping if I only have a function that can compare 2 elements. $\endgroup$list ~Extract~ Ordering[list, 1, p]
is a bit cleaner than your present formulation. $\endgroup$