This predicate assembles an ordered list of solutions of a goal for each different instantiation of the free variables in that goal. The list is ordered with the "term greater than" operator instead of the "term less than" operator that setof/3 uses.
The elements in each list are in term greater than order and
duplicates are removed from the list. The goal setof_reverse(X, Goal, List) will produce a
'List' of all the objects X such that the 'Goal' is satisfied. After each solution the
variables in the expression X 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 X, the ^ operator must be used
for that, for example: bagof(X, Var1 ^ Var2 ^ Goal, List). The ^
operator is a predefined infix operator.
Assume the database contains the user-defined predicates:
legs(A, 6) :- insect(A). legs(A, 4) :- animal(A). legs(A, 8) :- spider(A). insect(bee) :- true. animal(horse) :- true. animal(dog) :- true. spider(tarantula) :- true. age(peter, 7). age(ann, 5). age(pat, 8). age(tom, 5).
see also: bagof/3 ^/2 findall/3 setof/3 term order
| Examples | |
| setof_reverse(Child, age(Child, 5), List). | List = [tom, ann] |
| setof_reverse(Child, age(Child,Age), List). | Age = 7, List = [peter] Age = 5, List = [tom, ann] Age = 8, List = [pat] |
| setof_reverse(Child/Age, age(Child, Age), List). | List = [tom/5, peter/7, pat/8, ann/5] |
| setof_reverse(Child, Age ^ age(Child, Age), List). | List = [tom, peter, pat, ann] |
| setof_reverse(A, legs(A, N), List). | List = [bee] List = [horse, dog] List = [tarantula] |
| Exceptions | |
| The second argument must not be an empty variable | an instantiation_error is thrown |
| The second argument Arg is not a correct goal | a type_error(callable, Aarg) exception is thrown, Arg is replaced by the incorrect goal |
| Third argument Arg is not a list or a variable. | a type_error(list, Arg) exception is thrown, Arg is replaced by the incorrect third argument |