previous  next
SortBy, SortedBy
Syntax
SortBy(V:LIST,F:FUNCTION):NULL
SortedBy(L:LIST,F:FUNCTION):LIST

where V is a variable containing a list and F is a boolean-valued
function of two arguments.
Summary
sort a list
Description
The first function sorts the elements of the list in V with respect
to the comparisons made by F; it overwrites V.  The second function,
'Sorted', returns the list of the sorted elements of L without
affecting L, itself.  The function F takes two arguments and returns
TRUE or FALSE.  If F(A,B) returns TRUE, then 'SortBy' and 'SortedBy'
will place A before B in the sorted list.

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: