Richard
Richard

Reputation: 171

Prolog if sentence conditions

So basically I am trying to check in the middle of a rule if certain conditions are met but the condition depends on another variable.
In my case if the Num1 is 10, then the Num2 can't be 1 - if it is 1 then fail and if the Num1 is 20, then Num2 can't be 2.

This is something I came up with

do_function(Num1, Num2):-
   write('first'),
   ((Num1 = 10, Num2 \= 1); (Num1 = 20, Num2 \= 2)),
   write('last').

The query that it works with:

 ?- do_function(20, 1).
 firstlast
 true.

But with this query I get:

?- do_function(10, 2).
firstlast
true ;
false.

In this case it writes firstlast for some reason, but in my actual code it does the first part and then crashes, because of the false it gets.

Upvotes: 0

Views: 60

Answers (2)

Valera Grishin
Valera Grishin

Reputation: 441

Simply translating your rule (and assuming you meant N1 is 20):

In my case if the Num1 is 10, then the Num2 can't be 1 - if it is 1 then fail and if the Num2 is 20, then Num2 can't be 2.

to Prolog code:

do_function(N1, N2) :- N1 is 10, N2 \= 1.
do_function(N1, N2) :- N1 is 20, N2 \= 2.

or:

do_function(10, N2) :- N2 \= 1.
do_function(20, N2) :- N2 \= 2.

Upvotes: 1

Paulo Moura
Paulo Moura

Reputation: 18683

If you can ensure that the checking predicate is only called with bound arguments, then use the if-then-else control construct. E.g.

do_function(Num1, Num2) :-
    (   Num1 =:= 10 ->
        Num2 =\= 1
    ;   Num1 =:= 20 ->
        Num2 =\= 2
    ;   true
    ).

Also take a look to the library(clpfd). Depending on the problem that you're trying to solve, using constraints may be a better alternative.

Upvotes: 1

Related Questions