SORTsequence
(SORTsequence
predicate
)
Sorts a sequence (list, array, or word) in ascending order, or according to a given predicate.
The output is a new sequence of the same type as sequence
that contains the same items ordered such that there are no two successive items, a and b, where (
is FALSE and predicate
a b)(
is TRUE.
predicate
b a)
The predicate
input must be either an explicit-slot template or the name of a procedure that acts as the predicate.
The predicate must input two values and output either TRUE or FALSE.
If no predicate
input is given, then the predicate used depends on the sequence
input, as defined by the following table.
sequence type | output |
---|---|
A list of numbers | A list sorted by LESSP |
A list of non-numbers | A list sorted by BEFOREP |
An array of numbers | An array sorted by LESSP |
An array of non-numbers | An array sorted by BEFOREP |
A word | A word whose characters are sorted by BEFOREP |
Sorting in ascending order:
SHOW SORT [3 1 2]
[1 2 3]
Sorting in descending order:
SHOW (SORT [3 1 2] "GREATERP)
[3 2 1]
Sorting complex records:
; [name age height] MAKE "a [Ana 12 52] MAKE "b [Bob 11 54] MAKE "c [Cole 12 57] MAKE "d [Dan 12 52] MAKE "e [Erin 11 54] MAKE "data (LIST :e :d :c :b :a) ; Sort by height. SHOW (SORT :data [LESSP LAST ?1 LAST ?2])
[[Dan 12 52] [Ana 12 52] [Erin 11 54] [Bob 11 54] [Cole 12 57]]; Sort by height with ties sorted by name. SHOW (SORT (SORT :data [BEFOREP FIRST ?1 FIRST ?2]) [LESSP LAST ?1 LAST ?2])
[[Ana 12 52] [Dan 12 52] [Bob 11 54] [Erin 11 54] [Cole 12 57]]