Prolog:And-Or 表达式( bool 函数)

标签 prolog

我正在做作业需要实现两个关系 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 表达式运行?

最佳答案

如果你想自己做,以便它也能以生成方式工作(与 Ca​​pelliC 的回答中看到的“裸” 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/

相关文章:

Prolog 列表中的最大值

list - `memberd/2` 更具确定性?

prolog - 否定中的削减行为

list - 如何使用递归将多个头添加到列表

prolog - Prolog 中的二叉树

prolog - 证明 X 在 Y 之前 Prolog

prolog - 处理 SWI-Prolog 中的未知程序错误

prolog - 如何求六边形的对角线?

random - YAP Prolog random 缺乏随机性

Prolog - 列表中的序列