Google News
logo
Prolog - Interview Questions
What is the difference between bagof/3 and setof/3 predicates in Prolog?
In Prolog, both the `bagof/3` and `setof/3` predicates are used for generating sets of solutions to a query. However, there is a key difference between these two predicates in how they handle duplicate solutions. Here's an explanation of the difference between `bagof/3` and `setof/3`:

1. `bagof/3` Predicate :
   * The `bagof/3` predicate is used to generate a bag (i.e., a list) of solutions to a query.
   * It collects all possible solutions to a query, including duplicates, and stores them in a list.
   * The solutions in the resulting list are ordered based on the order of backtracking.
   * If there are no solutions, `bagof/3` will fail, and the resulting list will be empty.
   * Example:
     bagof(X, likes(X, pizza), PeopleWhoLikePizza).​

     This will generate a list of all individuals who like pizza, including duplicate entries if there are multiple individuals who like pizza.
2. `setof/3` Predicate :
   * The `setof/3` predicate is used to generate a sorted set of solutions to a query, removing any duplicates.
   * It collects all possible solutions to a query and creates a sorted set of unique solutions.
   * The resulting set is ordered based on the standard order of terms.
   * If there are no solutions, `setof/3` will fail, and the resulting set will be empty.
   * Example:
     setof(X, likes(X, pizza), UniquePeopleWhoLikePizza).​

     This will generate a sorted set of unique individuals who like pizza, removing any duplicate entries.
Advertisement