Enum.min_max_by
You're seeing just the function
min_max_by
, go back to Enum module for more information.
Link to this function
min_max_by(enumerable, fun, sorter_or_empty_fallback \\ &</2, empty_fallback \\ fn -> raise(Enum.EmptyError) end)
View SourceSpecs
min_max_by( t(), (element() -> any()), (element(), element() -> boolean()) | module(), (() -> empty_result) ) :: {element(), element()} | empty_result when empty_result: any()
Returns a tuple with the minimal and the maximal elements in the enumerable as calculated by the given function.
If multiple elements are considered maximal or minimal, the first one that was found is returned.
Examples
iex> Enum.min_max_by(["aaa", "bb", "c"], fn x -> String.length(x) end)
{"c", "aaa"}
iex> Enum.min_max_by(["aaa", "a", "bb", "c", "ccc"], &String.length/1)
{"a", "aaa"}
iex> Enum.min_max_by([], &String.length/1, fn -> {nil, nil} end)
{nil, nil}
The fact this function uses Erlang's term ordering means that the
comparison is structural and not semantic. Therefore, if you want
to compare structs, most structs provide a "compare" function, such as
Date.compare/2
, which receives two structs and returns :lt
(less-than),
:eq
(equal to), and :gt
(greater-than). If you pass a module as the
sorting function, Elixir will automatically use the compare/2
function
of said module:
iex> users = [
...> %{name: "Ellis", birthday: ~D[1943-05-11]},
...> %{name: "Lovelace", birthday: ~D[1815-12-10]},
...> %{name: "Turing", birthday: ~D[1912-06-23]}
...> ]
iex> Enum.min_max_by(users, &(&1.birthday), Date)
{
%{name: "Lovelace", birthday: ~D[1815-12-10]},
%{name: "Ellis", birthday: ~D[1943-05-11]}
}
Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback:
iex> Enum.min_max_by([], &String.length/1, fn -> nil end)
nil