Google News
logo
Prolog - Interview Questions
Explain the concept of logical negation in Prolog and how it is implemented.
In Prolog, logical negation refers to the ability to express and reason about the absence or negation of a certain condition or relationship. It allows you to state that a proposition or goal is not true or does not hold.

The concept of logical negation in Prolog is implemented through the use of the built-in predicate `not/1` or the operator `\+/1`. These constructs provide a way to express negation and perform negation as failure in Prolog.

The `not/1` predicate or `\+/1` operator work as follows:

1. `not/1` Predicate : The `not/1` predicate takes a single argument, which is the goal or condition to be negated. It succeeds if the goal cannot be proven (i.e., if the goal fails) and fails if the goal succeeds. It performs negation by attempting to prove the goal and backtracks if the goal succeeds, ensuring that it fails.

2. `\+/1` Operator : The `\+/1` operator is an alternative notation for negation in Prolog. It functions in the same way as `not/1`. It is used by placing it before a goal or condition that you want to negate. It succeeds if the goal fails and fails if the goal succeeds.
Here's an example to illustrate the usage of logical negation in Prolog:
likes(john, pizza).
likes(john, burger).

vegetarian(X) :- not(likes(X, meat)).

?- vegetarian(john).​


In this example, we have a `likes/2` predicate that represents John's food preferences. The `vegetarian/1` predicate is defined to determine if someone is a vegetarian. It uses the `not/1` predicate to express the negation of liking meat. If a person does not like meat, they are considered a vegetarian.

When the query `vegetarian(john)` is executed, Prolog attempts to prove the goal by executing the `not(likes(john, meat))` subgoal. Since John does not have any fact that states he likes meat, the subgoal fails, and the `vegetarian(john)` query succeeds.
Advertisement