我试图创建一个谓词,以验证给定的输入是否代表公式.
我被允许只使用像p,q,r,s,t等命题原子.我必须测试的公式如下:
neg(X) - represents the negation of X
and(X, Y) - represents X and Y
or(X, Y) - represents X or Y
imp(X, Y) - represents X implies Y
Run Code Online (Sandbox Code Playgroud)
我已经使谓词wff在给定结构是公式时返回true,否则返回false.另外,我不必在公式中使用变量,只提到下面提到的命题原子.
logical_atom( A ) :-
atom( A ),
atom_codes( A, [AH|_] ),
AH >= 97,
AH =< 122.
wff(A):-
\+ ground(A),
!,
fail.
wff(and(A, B)):-
wff(A),
wff(B).
wff(neg(A)):-
wff(A).
wff(or(A, B)):-
wff(A),
wff(B).
wff(imp(A, B)):-
wff(A),
wff(B).
wff(A):-
ground(A),
logical_atom(A),
!.
Run Code Online (Sandbox Code Playgroud)
当我引入类似这样的测试时
wff(and(q, imp(or(p, q), neg(p)))).,调用返回true和false值.你能告诉我为什么会这样吗?
mat*_*mat 10
您选择用于表示公式的数据结构称为"defaulty",因为您需要一个"默认"大小写来测试原子标识符:所有不属于上述内容(和,或者,neg,imp)并且满足logical_atom/1是一个逻辑原子(在你的表示中).解释器无法通过其仿函数来区分这些情况以应用第一参数索引.与类似的和/或/等相比,它更加清洁,它还将原子变量与它们的专用函子配对,比如"atom(...)".然后wff/1可以读取:
wff(atom(_)).
wff(and(A, B)) :- wff(A), wff(B).
wff(neg(A)) :- wff(A).
wff(or(A, B)) :- wff(A), wff(B).
wff(imp(A, B)) :- wff(A), wff(B).
Run Code Online (Sandbox Code Playgroud)
您的查询现在可以根据需要确定:
?- wff(and(atom(q), imp(or(atom(p), atom(q)), neg(atom(p))))).
true.
Run Code Online (Sandbox Code Playgroud)
如果您的公式最初没有以这种方式表示,那么首先将它们转换为这样的形式,然后使用这种非默认的表示形式进行进一步处理仍然会更好.
另一个优点是,您现在不仅可以轻松地测试,还可以使用以下代码枚举格式良好的公式:
wff(atom(_)) --> [].
wff(and(A,B)) --> [_,_], wff(A), wff(B).
wff(neg(A)) --> [_], wff(A).
wff(or(A,B)) --> [_,_], wff(A), wff(B).
wff(imp(A,B)) --> [_,_], wff(A), wff(B).
Run Code Online (Sandbox Code Playgroud)
和查询一样:
?- length(Ls, _), phrase(wff(W), Ls), writeln(W), false.
Run Code Online (Sandbox Code Playgroud)
产量:
atom(_G490)
neg(atom(_G495))
and(atom(_G499),atom(_G501))
neg(neg(atom(_G500)))
or(atom(_G499),atom(_G501))
imp(atom(_G499),atom(_G501))
and(atom(_G502),neg(atom(_G506)))
and(neg(atom(_G504)),atom(_G506))
neg(and(atom(_G504),atom(_G506)))
neg(neg(neg(atom(_G505))))
neg(or(atom(_G504),atom(_G506)))
neg(imp(atom(_G504),atom(_G506)))
etc.
Run Code Online (Sandbox Code Playgroud)
作为其输出.