使用运算符定义在序言中制作 op 有 'likes' 和 'and'
make op in prolog with operator definition theres have 'likes' and 'and'
我有信息知识库:
:- op(650,xfx,like).
john like cat.
john like dog.
john like bird.
mary like dog.
mary like horse.
mary like bird.
我需要谓词,当我写这样的代码时:
?- Who like dog and bird.
所以,return 会这样吗:
Who = john;
Who = mary.
我做一个这样的谓词:
:- op(700,xfx,and).
X and Y:- X,Y.
但是如果我想要 Who=john;,那么使用该代码我可以编写这样的代码。谁=mary 可以显示:
?-Who like dog and Who like bird.
Who like dog and bird
将被解释为:
(Who like dog) and bird
这将产生一个错误,因为 Prolog 试图查询 bird
没有与之关联的事实或规则。
| ?- Who like dog and bird.
uncaught exception: error(existence_error(procedure,bird/0),(and)/2)
如果您使 and
的优先级高于 like
,那么这将被读取为 Who like (dog and bird)
,这仍然会失败,但会更接近:
:- op(600, xfx, and).
| ?- Who like dog and bird.
no
这会失败,因为您的事实或谓词中没有任何内容可以处理复合直接宾语(... like (A and B)
没有匹配项。您现在需要的是处理复合项的谓词:
X like (A and B) :-
X like A,
X like B.
那么你会得到:
| ?- Who like dog and bird.
Who = john ? ;
Who = mary ? ;
no
| ?-
整个解决方案如下所示:
:- op(650, xfx, like).
:- op(600, xfx, and).
john like cat.
john like dog.
john like bird.
mary like dog.
mary like horse.
mary like bird.
X like (A and B) :-
X like A,
X like B.
X and Y :- X, Y.
我有信息知识库:
:- op(650,xfx,like).
john like cat.
john like dog.
john like bird.
mary like dog.
mary like horse.
mary like bird.
我需要谓词,当我写这样的代码时:
?- Who like dog and bird.
所以,return 会这样吗:
Who = john;
Who = mary.
我做一个这样的谓词:
:- op(700,xfx,and).
X and Y:- X,Y.
但是如果我想要 Who=john;,那么使用该代码我可以编写这样的代码。谁=mary 可以显示:
?-Who like dog and Who like bird.
Who like dog and bird
将被解释为:
(Who like dog) and bird
这将产生一个错误,因为 Prolog 试图查询 bird
没有与之关联的事实或规则。
| ?- Who like dog and bird.
uncaught exception: error(existence_error(procedure,bird/0),(and)/2)
如果您使 and
的优先级高于 like
,那么这将被读取为 Who like (dog and bird)
,这仍然会失败,但会更接近:
:- op(600, xfx, and).
| ?- Who like dog and bird.
no
这会失败,因为您的事实或谓词中没有任何内容可以处理复合直接宾语(... like (A and B)
没有匹配项。您现在需要的是处理复合项的谓词:
X like (A and B) :-
X like A,
X like B.
那么你会得到:
| ?- Who like dog and bird.
Who = john ? ;
Who = mary ? ;
no
| ?-
整个解决方案如下所示:
:- op(650, xfx, like).
:- op(600, xfx, and).
john like cat.
john like dog.
john like bird.
mary like dog.
mary like horse.
mary like bird.
X like (A and B) :-
X like A,
X like B.
X and Y :- X, Y.