projog

3.108. keysort(X,Y) - sorts a list of key/value pairs.

Sorts the list X, containing key/value pairs, and attempts to unify the result with Y. Key/value pairs are compound terms with a functor of - and two arguments. The first argument is the key and the second argument is the value. It is the key of the key/value pairs that is used to sort the elements contained in X. (Note: duplicates are not removed.)

Examples

?- keysort([a - 1,b - 3,c - 2], X).
X = [a - 1,b - 3,c - 2]

yes

?- keysort([c - 2,a - 1,b - 3], X).
X = [a - 1,b - 3,c - 2]

yes

?- keysort([c - 2,a - 1,b - 3], [a - 1,b - 3,c - 2]).

yes

?- keysort([c - 2,a - 1,b - 3], [c - 2,a - 1,b - 3]).

no

Duplicates are not removed.

?- keysort([a - 1,a - 9,a - 1,z - 1, q - 3, z - 1], X).
X = [a - 1,a - 9,a - 1,q - 3,z - 1,z - 1]

yes

Keys are sorted using the standard ordering of terms.

?- keysort([Variable - v,1.0 - v,1 - v,atom - v, [] - v,structure(a) - v,[list] - v], X).
Variable = UNINSTANTIATED VARIABLE
X = [Variable - v,1.0 - v,1 - v,[] - v,atom - v,structure(a) - v,[list] - v]

yes

?- keysort([[list] - v,structure(a) - v,[] - v,atom - v,1 - v,1.0 - v,Variable - v], X).
Variable = UNINSTANTIATED VARIABLE
X = [Variable - v,1.0 - v,1 - v,[] - v,atom - v,structure(a) - v,[list] - v]

yes

Both the first and second arguments can contain variables.

?- keysort([c - Q,a - W,b - E],[R - 1,T - 2,Y - 3]).
E = 2
Q = 3
R = a
T = b
W = 1
Y = c

yes