bagof(?Term, +Goal, -List)

Succeeds if List is the (non-empty) list of all instances of Term such that
Goal is provable.

Term

Prolog term, usually a variable, a compound term or list containing variables.

Goal

Callable term.

List

List or variable.

Description

Unifies List with the list (not ordered, duplicates retained) of all
instances of Term such that Goal is satisfied. The variables appearing
in Term should not appear anywhere else in the clause except within
Goal.

The following table illustrates the difference between the all solutions
predicates:

built-in choice pts duplicates sorted pruned *
bagof/3 yes yes no no
coverof/3 yes no no yes
findall/3 no yes no no
setof/3 yes no yes no
* prune_instances/2 used on list of solutions.

If Goal is not a callable term, exceptions are raised in call/2.

Note
If there are uninstantiated variables in Goal which do not appear in
Term, then bagof/3 can be resatisfied. It generates alternative values
for List corresponding to different instantiations of the free variables
of Goal not in Term. Such variables occurring in Goal will not be
treated as free if they are explicitly bound within Goal through an
existential quantification written as, for example,

bagof(X, Y^(X likes Y), S).

Then bagof/3 will not backtrack over Y when getting a bag of solutions
of X.

Modes and Determinism

bagof(?, +, -) is nondet

Modules

This predicate is sensitive to its module context (tool predicate, see @/2).