[ Comparing and Sorting | Reference Manual | Alphabetic Index ]
# keysort(+List1, -List2)

Succeeds if List2 is a sorted list version of List1, whose elements are of
the form Key-Value. The sort is done according to the value of the key
Key.
*List1*
- List of elements of the form Term-Term.
*List2*
- List or variable.

## Description

The elements of List1 are of the form Key-Value, where Key and Value are
both arbitrary terms.
List1 is sorted according to the value of the key Key and the result is
unified with List2. No sorting is carried out on Value. The sort is
stable, i.e. the order of elements with the same key is preserved.

The sort is done according to the standard ordering of terms.
See compare/3 for this standard ordering.
Note in particular that numbers are first ordered by their type (integer,
float, etc) and only then by their magnitude, i.e. sorting numbers of
different types may not give the expected result.

keysort(R, S) is equivalent to sort(1, =<, R, S).

### Modes and Determinism

### Exceptions

*(4) instantiation fault *
- List1 is not instantiated.
*(5) type error *
- Either List1 or List2 is instantiated, but not to a list of the form Term-Term.

## Examples

Success:
keysort([n-1,4-a],L). (gives L = [4-a,n-1]]).
keysort([f(1)-a,[1]-w,7.2-b,"k"-e,n-q],L).
(gives L = [7.2-b,"k"-e,n-q,f(1)-a,[1]-w]).
keysort([f(1,2),g(1)],M). (gives M = [f(1,2),g(1)]).
keysort([g(1,2)-a, f(1,2)-a],M).
(gives M = [f(1,2)-a,g(1,2)-a]).
keysort([f(4,3)-a, f(3,4)-b],M).
(gives M = [f(3,4)-b,f(4,3)-a]).
Fail:
keysort([n-1,M-a],[n-1,M-a]).
Error:
keysort(L1,L2). (Error 4).
keysort([n-1,m],L). (Error 5).

## See Also

compare / 3, merge / 3, merge / 5, msort / 2, sort / 4, number_sort / 4