Enum.max
max
, go back to Enum module for more information.
max(enumerable, sorter \\ &>=/2, empty_fallback \\ fn -> raise(Enum.EmptyError) end)
View SourceSpecs
max(t(), (element(), element() -> boolean()) | module(), (() -> empty_result)) :: element() | empty_result when empty_result: any()
Returns the maximal element in the enumerable
according
to Erlang's term ordering.
By default, the comparison is done with the >=
sorter function.
If multiple elements are considered maximal, the first one that
was found is returned. If you want the last element considered
maximal to be returned, the sorter function should not return true
for equal elements.
If the enumerable is empty, the provided empty_fallback
is called.
The default empty_fallback
raises Enum.EmptyError
.
Examples
iex> Enum.max([1, 2, 3])
3
The fact this function uses Erlang's term ordering means that the comparison is structural and not semantic. For example:
iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]])
~D[2017-03-31]
In the example above, max/2
returned March 31st instead of April 1st
because the structural comparison compares the day before the year.
For this reason, 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> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date)
~D[2017-04-01]
Finally, if you don't want to raise on empty enumerables, you can pass the empty fallback:
iex> Enum.max([], &>=/2, fn -> 0 end)
0