sort/4 in SWI-Prolog
Signature: sort(+Key, +Order, +List, -Sorted)
sort/4 is a generalized sorting predicate that lets you control two things the basic sort/2 doesn't: what part of each element to sort by (the key) and how to order and handle duplicates.
The Arguments
Key — which part of each element to compare. Common values:
0— use the entire term as the key1,2,3, … — use the Nth argument of a compound term (likef(A,B,C), where1picks A)- A list of keys (e.g.
[2,1]) — for deeper nested access Order — a combination of sort direction and duplicate handling:Order Direction Duplicates @<ascending remove @=<ascending keep @>descending remove @>=descending keep List — the input list.
Sorted — the resulting sorted list (output).
Simple Example
Say you have a list of person(Name, Age) terms and want to sort by age (the 2nd argument) in ascending order, removing duplicates:
?- sort(2, @<, [person(alice, 30), person(bob, 25), person(carol, 30)], Sorted). Sorted = [person(bob, 25), person(alice, 30)].
- Key
2means "compare on the 2nd argument" (the age). @<means ascending, with duplicate keys removed — soaliceandcarolboth have age30, and only the first one (alice) is kept. If you want to keep both people with age 30, use@=<:?- sort(2, @=<, [person(alice, 30), person(bob, 25), person(carol, 30)], Sorted). Sorted = [person(bob, 25), person(alice, 30), person(carol, 30)].
Relation to simpler predicates
sort/4 is a superset of the other sorting predicates. For instance:
sort(List, Sorted)is equivalent tosort(0, @<, List, Sorted)msort(List, Sorted)is equivalent tosort(0, @=<, List, Sorted)The sort is stable, meaning that among elements with equal keys, their original relative order is preserved when using a "keep" order (@=<or@>=).
Credits
Produced by Claude.