none
A question about List.Sort function RRS feed

  • Question

  • Hi,

    Can anybody explain the 2end parameter of List.Sort

    the Official explanation:

    To completely control the comparison, a function with two 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.

    But how to understand the following :

    List.Sort({1..9},(x,y)=>(3*x,2*y)) = {1,3,2,7,6,5,4,8,9}    

    Monday, October 10, 2016 5:53 AM

Answers

  • Hi,

    I think your example is missing "Value.Compare" and should be

    List.Sort({1..9},(x,y)=>Value.Compare(3*x,2*y)) = {1,3,2,7,6,5,4,8,9}

    This is an interesting example since the comparison function is not symmetric.

    I can't say for sure what algorithm List.Sort uses, but in this case it has produced a list

    {item(1), item(2),...,item(9)} = {1,3,2,7,6,5,4,8,9}

    such that Value.Compare( 3*item(n), 2*item(n-1) ) ∈ {0,1} for all n=2,...,9,

    i.e. each item(n) ">=" item(n-1), which we would expect from a sorted list.

    However, it isn't the case that Value.Compare( 3*item(n-1), 2*item(n) ) ∈ {0,-1} for all n=2,...9

    i.e. it isn't always true that item(n-1) "<=" item(n)

    Perhaps someone knows exactly how List.Sort works when the second argument is not a symmetric function?

    Does it first try to find an ordering such that ComparisonFunction( item(n), item(n-1) ) ∈ {0,1}?



    Owen Auger, CFA https://nz.linkedin.com/in/owenauger


    Monday, October 10, 2016 12:41 PM
  • List.Sort shouldn't be relied on to produce any particular output when given an asymmetric comparison function.
    Tuesday, October 11, 2016 7:12 PM

All replies

  • Hi,

    I think your example is missing "Value.Compare" and should be

    List.Sort({1..9},(x,y)=>Value.Compare(3*x,2*y)) = {1,3,2,7,6,5,4,8,9}

    This is an interesting example since the comparison function is not symmetric.

    I can't say for sure what algorithm List.Sort uses, but in this case it has produced a list

    {item(1), item(2),...,item(9)} = {1,3,2,7,6,5,4,8,9}

    such that Value.Compare( 3*item(n), 2*item(n-1) ) ∈ {0,1} for all n=2,...,9,

    i.e. each item(n) ">=" item(n-1), which we would expect from a sorted list.

    However, it isn't the case that Value.Compare( 3*item(n-1), 2*item(n) ) ∈ {0,-1} for all n=2,...9

    i.e. it isn't always true that item(n-1) "<=" item(n)

    Perhaps someone knows exactly how List.Sort works when the second argument is not a symmetric function?

    Does it first try to find an ordering such that ComparisonFunction( item(n), item(n-1) ) ∈ {0,1}?



    Owen Auger, CFA https://nz.linkedin.com/in/owenauger


    Monday, October 10, 2016 12:41 PM
  • List.Sort shouldn't be relied on to produce any particular output when given an asymmetric comparison function.
    Tuesday, October 11, 2016 7:12 PM