如果给定的 prolog 谓词返回 true 或 false,我如何打印语句。
statement(X,Y) = true -> write("The statement is true").
谢谢!
答案 0 :(得分:1)
您按预期使用 Prolog(我将使用 format/2 而不是 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)",[]).
第二个条款是危险的。如果在一个目标上使用 negaion-as-failure \+
,该目标的变量是非地面的并且在该目标之外可见,Prolog 很可能会给出错误的答案(这被称为“挣扎”)
因此:
% 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!",[]).
请注意,我们可以使用切割 !
以更简单的方式编写此代码。这样,一个人只需要调用 statement(X,Y)
一次。如果调用成本高昂或有副作用,或者出于美观考虑,这可能是必要的:
% 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!",[]).
答案 1 :(得分:0)
您可以使用 if-else。
prolog 程序检查 X 是否等于 Y,如果为真则打印语句 The statement is true
,否则打印语句 The statement is false
。
statement(X,Y):-
( X==Y ->
write('The statement is true');
write('The statement is false')).
示例:
?- statement(3,3).
The statement is true
1true
?- statement(3,45).
The statement is false
1true