Documentation Prolog Predicate Reference builtin bagof/3

bagof/3

Find all the values that would make a goal succeed and structure them.

Description

bagof( ?term, +callable_term, ?list )

bagof(Template, Goal, Instances) works similarly to findall/3. The only difference is that, for bagof/3, Instances is a list of lists, being each sublist made up of the values that unify with Goal for a specific value (or values, depending on the number of variables in Goal). That is, bagof/3 create a sublist in Instances for each free variable of Goal that is not in Template. Also, if Goal has no solution, bagof/3 will fail.
bagof/3 can be used like findall/3 by using the existencial operator ^, which is used to indicate what variables of Goal must not be bound. This way, if we write, in the Goal argument, all the free variables in the goal that are not in Template separated by ^, the result would be the same that if we call findall/3.

Implementation