Predicate: group_by/4

data(a,1).
data(b,2).
data(b,3).
data(a,4).
?- group_by(A, B, data(A,B), Bag).
A = a,
Bag = [1, 4] ;
A = b,
Bag = [2, 3].