Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog: And-Or expressions (boolean function)

Tags:

prolog

I am doing a homework need to implement two relations and(A,B) and or(A,B) that perform the logical “AND” and the logical “OR” operations on two Boolean operands A and B. Relation and(A,B)holds if A and B both evaluate to true. Relation or(A,B)holds if either A or B evaluates to true, or both A and B evaluate to true. An And-OR expression can be nested, e.g., and(or(A,B),and(C,D)).

Some sample input and output:

?- 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.

My code:

and(true,true).
and(false,_):-false.
and(_,false):-false.
or(true,_).
or(_,true).
or(false,false):-false.

When I run the simple and-or expressions, it is ok. But when I run some expressions included nested and-or expressions, it just give "false" as the answer. How can I correct the code so that it can run with nested and-or expressions?

like image 961
Peter Avatar asked Nov 20 '13 18:11

Peter


1 Answers

If you want to do it yourself, so that it works also in generative fashion (unlike the "naked" Prolog code as seen in CapelliC's answer), then:

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?

this works almost exactly as you've shown:

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.
like image 189
Will Ness Avatar answered Oct 25 '22 11:10

Will Ness