setof
Setof is a Prolog built-in predicate used to collect all solutions of a goal into a single, sorted, deduplicated list. It has the form setof(Template, Goal, Set). Set is the list of all instances of Template that make Goal true, with duplicates removed and the results ordered according to the standard term order.
Key points about its behavior:
- Template specifies the form of the elements to collect. Each solution of Goal yields one Template,
- Variables that appear in Goal but do not appear in Template are treated as existentially quantified.
- Setof returns a single Set for the current binding of existential variables; it fails if there
- The produced Set is sorted and contains no duplicates, forming a true “set” in the mathematical
- setof(X, member(X, [a, b, a]), S). S = [a, b].
- color(apple, Color). Facts: color(apple, red). color(apple, green). Then setof(Color, color(apple, Color), Colors) yields Colors = [green, red].
- bagof/3 behaves similarly but groups results according to the values of existential variables, producing separate sets
- findall/3 collects all solutions without sorting or removing duplicates.