setof
The built-in Prolog predicate setof(+Template, +Goal, -Set) binds Set to the list of all instances of Template satisfying the goal Goal.

For example, given the facts and rule:

happy(fido).
happy(harry).
happy(X) :- rich(X).
rich(harry).

it follows that

?- setof(Y, happy(Y), Set).
Y = _G180
Set = [fido, harry] ;
false.

Notice that:

Compare:

?- bagof(Y, happy(Y), Bag).
Y = _G180
Bag = [fido, harry, harry] ;
false.
and
?- findall(Y, happy(Y), Bag).
Y = _G180
Bag = [fido, harry, harry] ;
false.

The differences between bagof and findall on the one hand, and setof on the other hand, include the fact that with setof, you get sorted order and no repetitions. (For differences between bagof and findall, see findall.)

setof will fail (and so not bind Set) if the there are no instances of Template for which Goal succeeds - i.e. effectively it fails if Set would be empty. bagof also fails in these circumstances, while findall does not (it binds the variable that is its third argument to the empty list, or, if the third argument is instantiated, it succeeds if the third argument is the empty list).