当前位置: 动力学知识库 > 问答 > 编程问答 >

Boolean AND in prolog returns X=true but the function becomes false

问题描述:

and_true(true, true).

and_false(false,true).

and_false(true,false).

and_false(false, false).

g_AND(Y,Z,X):- and_true(Y,Z), X=true.

g_AND(Y,Z,X):- and_false(Y,Z), X=false.

The only problem with this is that when I enter g_AND(true,true,X) it gives me

X=true ;

false

I don't want it to return the false. Can you help?

网友答案:

generally you trying to set "false become true when one of element is false". in your function g_AND(Y,Z,X) false becoming true, because your and_false(Y,Z) statement becoming true after giving false statement into one of variables.

try this code to make 'false become false'

and_true(true, true).

g_and(X,Y,Z):-
    and_true(X,Y),and_true(X,Z).

this code makes false when one of wariable is false, like natural AND.

网友答案:
g_AND(true,true,X).
X=true ; 
false

The false. means that it run out of results. The query and_true(true, true). is true and then it backtracked, looking for other statements that g_AND(true,true,X) will answer true in your file but it didn't find any, so it returned false. ( In some older versions of Prolog, you might get yes and no)

If you edit your file and add a cut ( ! ):

g_AND(Y,Z,X):- and_true(Y,Z), X=true, !.

The result will be just true.

2 ?- g_AND(true,true,X).
X = true.

Because, after the first result, the program will stop backtracking (It won't search for other answers).

分享给朋友:
您可能感兴趣的文章:
随机阅读: