[ library(lists_of_structures) | Reference Manual | Alphabetic Index ]

group_by_key(+Key, +Structs, -Grouped)

Partition a list into sublists by key
Key argument position (non-negative integer, or list of those)
List of structures
Variable, or list of list of structures


The list Structs is partitioned into maximal sublists of consecutive elements with identical keys. Concatenating all these sublists will yield the original list. If the original list was ordered according to the Key'th argument, then the sublists represent a partitioning of the original elements according to their different key values.

Modes and Determinism


(4) instantiation fault
Arguments are insufficiently instantiated
(5) type error
Some argument or its components are of the wrong type
(6) out of range
Some structure does not have a Key'th argument


    ?- group_by_key(1, [f(a,1),f(a,2),f(b,2),f(c,2),f(c,5)], Groups).
    Groups = [[f(a,1),f(a,2)], [f(b,2)], [f(c,2),f(c,5)]]
    Yes (0.00s cpu)

    ?- group_by_key(2, [f(a,1),f(a,2),f(b,2),f(c,2),f(c,5)], Groups).
    Groups = [[f(a,1)], [f(a,2),f(b,2),f(c,2)], [f(c,5)]]
    Yes (0.00s cpu)

    ?- group_by_key(1, [a-1,a-2,b-2,c-2,c-5], Groups).
    Groups = [[a-1,a-2], [b-2], [c-2,c-5]]
    Yes (0.00s cpu)

See Also

group_with_key / 3, same_key_prefix / 5, sort / 4, merge / 5