Reputation: 171
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
Reputation: 441
Simply translating your rule (and assuming you meant N1
is 20):
In my case if the
Num1
is 10, then theNum2
can't be 1 - if it is 1 then fail and if theNum2
is 20, thenNum2
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
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