Enum.sort_by behavior for decimal values inside a list of maps


Let’s say I have the following list of maps:

result = [%{str: "Mike", val: #Decimal<3>}, %{str: "Zed", val: #Decimal<-10>}, %{str: "Alex", val: #Decimal<10>}]

When I try sorting that list by val, like so:

Enum.sort_by(result, &(&1.val), {:desc, Decimal})

I’m getting:

[%{str: "Zed", val: #Decimal<-10>}, %{str: "Mike", val: #Decimal<3>}, %{str: "Alex", val: #Decimal<10>}]

However, it works as intended when I sort by str key (with String value).

My assumption was that specifying the order and module as a third argument to .sort_by would apply that module’s .compare function to pairs of Decimal values and sort them in a correct order. Apparently, that’s not the case. Am I missing something?


1 Like

Decimal.compare/2 doesn’t return the expected value by Enum in stable version (1.8.1). It was fixed and released as a release candidate.

I guess I could you Decimal.cmp/2 for now. Thanks again!