【问题标题】:Prolog: And-Or expressions (boolean function)Prolog:And-Or 表达式(布尔函数)
【发布时间】:2013-11-21 04:36:49
【问题描述】:

我正在做一个作业,需要实现两个关系和(A,B)和或(A,B),它们对两个布尔操作数 A 和 B 执行逻辑“与”和逻辑“或”运算。关系和(A,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 表达式运行?

【问题讨论】:

    标签: prolog


    【解决方案1】:

    如果您想自己做,以便它也以生成方式工作(与 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.
    

    【讨论】:

      【解决方案2】:

      当然,你需要完成对你的DSL(Domain Specific Language)语法树的访问,或者让Prolog利用这些基本规则:可以很简单

      and(L,R) :- L,R.
      or(L,R) :- L;R.
      

      产生

      1 ?- and(true,or(false,true)).
      true.
      
      2 ?- and(true,or(false,false)).
      false.
      

      【讨论】:

      • 这对于像and(A,true). 等非地面术语来说失败了; OP希望他们也能工作。 :)
      • @WillNess:是的,我忽略了这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2017-02-03
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多