Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

question from:https://stackoverflow.com/questions/66066294/how-to-print-a-write-value-given-prolog-predicate-retuns-true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
222 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!",[]).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...