Reputation: 21
How can I print a statement if a given prolog predicate returns true or false.
statement(X,Y) = true -> write("The statement is true").
Thanks!
Upvotes: 2
Views: 751
Reputation: 878
You can use if-else.
The prolog program checks if X is equal to Y, if true then print the statement The statement is true
, else print the statement The statement is false
.
statement(X,Y):-
( X==Y ->
write('The statement is true');
write('The statement is false')).
Example:
?- statement(3,3).
The statement is true
1true
?- statement(3,45).
The statement is false
1true
Upvotes: 0
Reputation: 15316
You use Prolog as intended (I will use format/2 instead of the write/1)
% if statement(X,Y) succeeds, Prolog will continue after the ","
% and call format/2
with_print(X,Y) :-
statement(X,Y),
format("The call succeeds (and the statement is presumably true)",[]).
% if statement(X,Y) fails, Prolog will continue after the ","
% and call format/2
with_print(X,Y) :-
\+statement(X,Y),
format("The call fails (and the statement is presumably false)",[]).
The second clause is dangerous. If use negaion-as-failure \+
on a goal that has variables that are nonground and visible outside that goal, Prolog may well give you incorrect answers (this is known as "floundering")
Therefore:
% if statement(X,Y) succeeds, Prolog will continue after the ","
% and call format/2
with_print(X,Y) :-
statement(X,Y),
format("The call succeeds (and the statement is presumably true)",[]).
% if statement(X,Y) fails, \+statement(X,Y) succeeds and
% Prolog will continue after the "," and call format/2
with_print(X,Y) :-
ground(X),
ground(Y),
\+statement(X,Y),
format("The call fails (and the statement is presumably false)",[]).
% what do you want to do in this case? it depends
with_print(X,Y) :-
(\+ground(X);\+ground(Y)),
format("I don't know what to do!",[]).
Note that we can write this in a simpler way using the cut !
. This way, one needs to call statement(X,Y)
only once. This may necessary if the call is expensive or has side-effects, or a matter of aesthetics:
% If statement(X,Y) succeeds, Prolog will continue after the ",",
% commit to this clause due to "!", and call format/2
with_print(X,Y) :-
statement(X,Y),
!,
format("The call succeeds (and the statement is presumably true)",[]).
% If the call statement(X,Y) in the clause above failed, we arrive here.
% Commit to the clause with "!" after testing for groundedness.
with_print(X,Y) :-
ground(X),
ground(Y),
!,
format("The call fails (and the statement is presumably false)",[]).
% What do you want to do in the "else" case? it depends!
with_print(_,_) :-
format("I don't know what to do!",[]).
Upvotes: 1