bagof(?term, +body_term, ?list) [ISO]

This predicate assembles a list of solutions for each different instantiation of the free variables in a goal. The elements in the list are in order of finding the solution.

The goal bagof(Term, Goal, List) will produce a 'List' of all the expressions 'term' such that the 'Goal' is satisfied. After each solution the variables in the expression 'term' are made empty so that a new solution can be found, other variables retain their values.

It is possible to specify that a variable must be made empty after a solution without specifying it in the goal 'Goal', the ^ operator must be used for that, for example:

    bagof(X, Var1 ^ Var2 ^ Goal, List).

The ^ operator is a predefined infix operator. If the 'Goal' expression contains any ^ operators then it must be rightmost goal of the expression. For example: the expression 'X ^ goal(Q)' is correct and 'goal(Q) ^ X' is not correct.

Assume the database contains the user-defined predicates:

see also: ^/2 findall/3 setof/3 setof_reverse/3

Examples
bagof(Child, age(Child, 5), List). List = [ann, tom]
bagof(Child, age(Child,Age), List). Age = 7, List = [peter]
Age = 5, List = [ann, tom]
Age = 8, List = [pat]
bagof(Child/Age, age(Child, Age), List). List = [peter/7, ann/5, pat/8, tom/5]
bagof(Child, Age ^ age(Child, Age), List). List = [peter, ann, pat, tom]
bagof(A, legs(A, N), List). List = [bee]
List = [horse, dog]
List = [tarantula]

 

Exceptions
third argument is not a list or a variable. a type_error(list, A) exception is thrown, A is replaced by the incorrect third argument
the second argument must not be an empty variable an instantiation_error is thrown.
the second argument is not a correct goal a type_error(callable, A) exception is thrown, A is replaced by the incorrect goal

 

 

info@trinc-prolog.com