Swap cmp/2 and compare/2 functions implementation to allow Enum to work with Decimal
sezaru opened this issue · comments
Elixir 1.10 allows now to send a module to functions like Enum.max, Enum.min, Enum.sort, etc.
One example is for Date:
Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date)
~D[2017-04-01]
This works because module Date
implements a compare/2
function that returns :lt
, :gt
or :eq
.
Decimal provides the same via cmp/2
function. compare/2
function returns 1, 0 or -1.
Since this approach by the core is the standard way to allow Enum functions to work out-of-the-box with any Type that implements the compare/2
function correctly, I proposing that we swap the cmp/2
and compare/2
functions, that way we can allow Decimal
to simply work with Enum
module from now on.
This would allow us to write code as:
Enum.max([Decimal.new("0.07278400"), Decimal.new("0.07799800")], Decimal)
Instead of:
Enum.max([Decimal.new("0.07278400"), Decimal.new("0.07799800")], &(Decimal.cmp(&1, &2) == :gt))
I know this is a very big change that can break people code, but I would argue that it is worth it since developers would assume that the compare/2
function returns :gt
, :lt
or :eq
as the rest of the standard library does.
PS. more info about this change can be seen here in the documentation: https://hexdocs.pm/elixir/Enum.html#max/3
this is already done on master which tracks Decimal v2.0.0-dev. Thanks!