sasha199568
sasha199568

Reputation: 1153

Generate negated values in Prolog

Here is what I am trying to accomplish

fact(f1p1, f1p2).
fact(f2p1, f2p2).
fact(f3p1, f3p2).

factIsNotTrue(Param1, Param2) :-
    \+fact(Param1, Param2).

I want the code above to produce the following

?- fact_is_not_true(f1p1, Param2).
Param2 = f2p2.
Param2 = f3p2.

Instead I get

?- fact_is_not_true(f1p1, Param2).
false.

Upvotes: 1

Views: 58

Answers (2)

Limmen
Limmen

Reputation: 1457

factIsNotTrue(Param1, Param2) :-
    \+fact(Param1, Param2).

The snippet above means "factIsNotTrue relation holds between Param1 and Param2 if fact(Param1, Param2) is not provable.

When you query factIsNotTrue(f1p1, Param2). Obviosuly prolog finds that fact(f1p1, f1p2) is in fact provable so the query fails.

You can modify your code as follows to generate the negated values:

param(f1p1).
param(f1p2).
param(f2p1).
param(f2p2).
param(f3p1).
param(f3p2).

fact(f1p1, f1p2).
fact(f2p1, f2p2).
fact(f3p1, f3p2).

factIsNotTrue(Param1, Param2):-
    param(Param1),
    param(Param2),
    \+ fact(Param1, Param2).

Test run:

?- factIsNotTrue(f1p1, Param2).
Param2 = f1p1 ;
Param2 = f2p1 ;
Param2 = f2p2 ;
Param2 = f3p1 ;
Param2 = f3p2.

?- factIsNotTrue(f1p1, f1p2).
false.

Upvotes: 2

Fatalize
Fatalize

Reputation: 3543

factIsNotTrue(Param1, Param2) :-
    dif(Param1, F),
    fact(F, Param2),
    \+ fact(Param1, Param2).

Here we say that Param2 is true for fact(F, Param2) and false for fact(Param1, Param2), and that Param1 is different from F using dif/2.

Sidenote

You may want to give clearer names to your variables in your code: Param1 and Param2 are probably not the most descriptive names.

We also recommend to name predicates using this_formatting_convention rather than thisFormattingConvention. It tends to make things more readable.

Upvotes: 2

Related Questions