Search code examples
prolog

How to solve equations with negation in prolog


I've tried to solve a simple problem in prolog: choose an object which is green but isn't round shape. So I wrote this code:

is_good(Item) :-
    not(round(Item)),
    green(Item).

round(melon).
round(umbrella).
round(ball).

green(melon).
green(bow).

Trying to solve this, I got:

is_good(bow).
true        %% "bow" is the correct answer
is_good(melon).
false
is_good(X). %% Here we trying to find an appropriate item
false       %% and fail

So, there is one solution, but we have to check it manually. But when I changed code to this (no negation):

is_good(Item) :-
    round(Item),
    green(Item).

round(melon).
round(umbrella).
round(ball).

green(melon).
green(bow).

All works perfectly fine:

is_good(bow).
false
is_good(melon).
true            %% "melon" is the correct answer
is_good(X).     %% Here we trying to find an appropriate item
X = melon       %% and success

Solution

  • Simply need to instantiate the variable first:

    ?- green(Item), \+ round(Item).
    Item = bow.