我正在做作业需要实现两个关系 and(A,B) 和 or(A,B),它们对两个 bool 操作数 A 和 B 执行逻辑“AND”和逻辑“OR”操作。 B) 如果 A 和 B 都评估为真,则成立。如果 A 或 B 评估为真,或者 A 和 B 评估为真,则关系 or(A,B) 成立。 And-OR 表达式可以嵌套,例如 and(or(A,B),and(C,D))。
一些示例输入和输出:
?- and(true,false).
false.
?- or(true,false).
true.
?- and(A,true).
A = true ;
false.
?- or(A,B).
A = true ;
B = true ;
false.
?- and(or(A,B),and(C,D)).
A = true,
C = true,
D = true ;
B = true,
C = true,
D = true ;
false.
?- or( and(or(A,B),C), or(and(D,E),or(F,G)) ).
A = true,
C = true ;
B = true,
C = true ;
D = true,
E = true ;
F = true ;
G = true ;
false.
我的代码:
and(true,true).
and(false,_):-false.
and(_,false):-false.
or(true,_).
or(_,true).
or(false,false):-false.
当我运行简单的 and-or 表达式时,就可以了。但是当我运行一些包含嵌套和-或表达式的表达式时,它只会给出“false”作为答案。如何更正代码以便它可以使用嵌套的 and-or 表达式运行?
最佳答案
如果你想自己做,以便它也能以生成方式工作(与 CapelliC 的回答中看到的“裸” Prolog 代码不同),那么:
and(A,B):- is_true(A), is_true(B).
or(A,B):- is_true(A) ; is_true(B).
is_true(true). %// no need to include any cases with false, it'll fail anyway
is_true(A):- var(A), !, false. %// prevent it from generating too much stuff
is_true(and(A,B)):- and(A,B).
is_true(or(A,B)):- ... . %// can you guess what to write here?
这几乎与您所展示的完全一样:
14 ?- and(true,false).
false.
15 ?- or(true,false).
true ; %// an extra choice point
false.
16 ?- and(A,true). %// works in generative fashion as well
A = true ;
false.
17 ?- or(A,B).
A = true ;
B = true ;
false.
18 ?- and(or(A,B),and(C,D)).
A = C, C = D, D = true ;
B = C, C = D, D = true ;
false.
19 ?- or( and(or(A,B),C), or(and(D,E),or(F,G)) ).
A = C, C = true ;
B = C, C = true ;
D = E, E = true ;
F = true ;
G = true ;
false.
关于Prolog:And-Or 表达式( bool 函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104042/