I want to understand Comparison Criteria: completely control the comparison, like: List.Sort({2, 3, 1}, (x, y) => Value.Compare(1/x, 1/y))

Miguel Caballero Sierra 171 Reputation points MVP
2021-08-18T03:06:47.877+00:00

I have been studying the Comparison Criteria in List functionsin in M languague, but the last one at the bottom on this page: https://learn.microsoft.com/en-us/powerquery-m/list-functions , says:

“To completely control the comparison, a function of 2 arguments can be used that returns -1, 0, or 1 given the relationship between the left and right inputs. Value.Compare is a method that can be used to delegate this logic”

The example in List.Sort is:

c0 =  
List.Sort (   
    { 2, 3, 1 },  
    ( x, y) => Value.Compare ( 1/x, 1/y )  
)  

// Witch return: { 3, 2, 1 }

But later I create this case:

c1 =   
List.Sort (  
    { -2, -1, 0, 1, 2 },  
    ( x, y ) =>  
    Value.Compare (   
        Number.Abs ( x ),  
        Number.Acos ( y )  
     )  
)  

// Witch return: { -2, 1, 0, 2, -1 }

Bit if I change the order of the input, like:

c2 =   
List.Sort (  
    { 2, -1, 1, 0, -2 },  
    ( x, y ) =>  
    Value.Compare (   
        Number.Abs ( x ),  
        Number.Acos ( y )  
     )  
)  

// The result is: { 2, 1, 0, -2, -1 }

Maybe the example with Number.Abs and Number.Acos is to rare, but what about this case:

c2 =  
List.Sort (  
    { 2, 7, -2, 4 },  
    ( a, b ) =>          
    Value.Compare (  
        -a,  
        Number.Power (b, 2 )  
    )  
)  

// Result: { 4, -2, 7, 2 }

I really would like to understand
Thanks a lot

  • Miguel Caballero
Not Monitored
Not Monitored
Tag not monitored by Microsoft.
36,526 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ehren (MSFT) 1,781 Reputation points Microsoft Employee
    2021-08-24T21:31:23.347+00:00

    Your comparer in the latter examples is asymmetric. Calling yourComparer(val1, val2) should equal -yourComparer(val2, val1).