SORT

Synopsis
SORT sequence
(SORT sequence predicate)
Description

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 (predicate a b) is FALSE and (predicate b a) is TRUE.

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 typeoutput
A list of numbersA list sorted by LESSP
A list of non-numbersA list sorted by BEFOREP
An array of numbersAn array sorted by LESSP
An array of non-numbersAn array sorted by BEFOREP
A wordA word whose characters are sorted by BEFOREP

Example

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]]


SourceForge.net Logo