up previous next
SortedBy

sort a list
Syntax

SortedBy(L:LIST, F:FUNCTION):LIST

where V is a variable containing a list and F is a boolean-valued
comparison function of two arguments (e.g. representing less than).


Description
This function returns the list of the sorted elements of L without affecting L, itself. As for SortBy , the comparison function F takes two arguments and returns TRUE if the first argument is less than the second, otherwise it returns FALSE. The sorted list is in increasing order.

Note that if both F(A, B) and F(B, A) return TRUE, then A and B are viewed as being equal.

Example
  Define ByLength(S, T)    -- define the sorting function
    Return Len(S) > Len(T);
  EndDefine;
  M := ["dog","mouse","cat"];
  SortedBy(M, Function("ByLength"));
["mouse", "dog", "cat"]
-------------------------------
  M;  -- M is not changed
["dog", "mouse", "cat"]
-------------------------------
  Sorted(M);  -- the function "Sort" sorts using the default ordering:
              -- in this case, alphabetical order.
["cat", "dog", "mouse"]
-------------------------------
  SortBy(M, Function("ByLength"));  -- sort M in place, changing M
M;
["mouse", "dog", "cat"]
-------------------------------


See Also