4.29 Built-in list operations
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
      • Built-in Predicates
        • Built-in list operations
          • is_list/1
          • memberchk/2
          • length/2
          • sort/2
          • sort/4
          • msort/2
          • keysort/2
          • predsort/3
    • Packages
Availability:built-in
sort(+Key, +Order, +List, -Sorted)
True when Sorted can be unified with a list holding the element of List. Key determines which part of each element in List is used for comparing two term and Order describes the relation between each set of consecutive elements in Sorted.140The definition of this predicate was established after discussion with Joachim Schimpf from the ECLiPSe team. ECLiPSe currently only accepts <, =<, > and >= for the Order argument but this is likely to change. SWI-Prolog extends this predicate to deal with dicts.

If Key is the integer zero (0), the entire term is used to compare two elements. Using Key=0 can be used to sort arbitrary Prolog terms. Other values for Key can only be used with compound terms or dicts (see section 5.4). An integer key extracts the Key-th argument from a compound term. An integer or atom key extracts the value from a dict that is associated with the given key. A type_error is raised if the list element is of the wrong type and an existence_error is raised if the compound has not enough argument or the dict does not contain the requested key.

Deeper nested elements of structures can be selected by using a list of keys for the Key argument.

The Order argument is described in the table below:141For compatibility with ECLiPSe, the values <, =<, > and >= are allowed as synonyms.

OrderOrderingDuplicate handling
@< ascendingremove
@=< ascendingkeep
@> descendingremove
@>= descendingkeep

The sort is stable, which implies that, if duplicates are kept, the order of duplicates is not changed. If duplicates are removed, only the first element of a sequence of duplicates appears in Sorted.

This predicate supersedes most of the other sorting primitives, for example:

sort(List, Sorted)     :- sort(0,  @<, List,  Sorted).
msort(List, Sorted)    :- sort(0, @=<, List,  Sorted).
keysort(Pairs, Sorted) :- sort(1, @=<, Pairs, Sorted).

The following example sorts a list of rows, for example resulting from csv_read_file/2) ascending on the 3th column and descending on the 4th column:

    sort(4, @>=, Rows0, Rows1),
    sort(3, @=<, Rows1, Sorted).

See also sort/2 (ISO), msort/2, keysort/2, predsort/3 and order_by/2.