The following predicates do a grouping of the solutions and may succeed more than once. This grouping is based on the determination of the witnesses of a solution. The witness are the global variables of T^G where T is the template and G is the goal.

Examples:
`p(a,y). p(a,x). p(b,x).?- bagof(X, p(X, Y), L).Y = y, L = [a] ;Y = x, L = [a, b]?- bagof(X, Y^p(X, Y), L).L = [a, a, b]`

The predicate bagof/3 will do a sorting of the witnesses but not of the resulting lists. The varia-tion setof/3 will sort the witnesses and the resulting lists. The variations bagof/4 and setof/4 allow specifying sort options.

Examples:
`?- bagof(Y, p(X, Y), L).X = a, L = [y, x] ;X = b, L = [x]?- setof(Y, p(X, Y), L).X = a, L = [x, y] ;X = b, L = [x]`

The predicate copy_term/2 can be used to copy a term. The predicates findall/[3,4] can be used to collect a resulting list without any grouping. The elements will be copied. The predicates foreach/2 and foreach/4 use findall/3 to compute a dynamic conjunction.

The following bags predicates are provided:

bagof(T, X1^…^Xn^G, L): [ISO 8.10.2]
bagof(T, X1^…^Xn^G, L, O):
The predicate determines all the solutions to the matrix G, whereby collecting copies of the template T grouped by the witnesses in a list. The predicate then repeatedly succeeds by unifying the witnesses and when L unifies with the corresponding list. The quaternary predicate takes additional sort options as argument.
setof(T, X1^…^Xn^G, L): [ISO 8.10.2]
setof(T, X1^…^Xn^G, L, O):
The predicate determines the same lists as the predicate bagof/3. But before returning them the lists are sorted by means of the predicate sort/2. The quaternary predicate takes additional sort options as argument.
foreach(F, G):
Calls the conjunction of those goal instances of G where F succeeds. Variables occur-ring in G and not occurring in F are shared.
foreach(F, G, I, O):
Calls the conjunction of those closure instances of G where F succeeds threading them with input I and output O. Variables occurring in G and not occurring in F are shared.