在 Prolog 中使用具有不同/不存在的事实的 OR 运算符
Using OR operator with different / non existent facts in Prolog
我有一个事实:
loves(romeo, juliet).
然后我有一个 'or' 规则:
dances(juliet) :- loves(romeo, juliet).
dances(juliet) :- dancer(juliet).
如您所见,dancer 的事实并不存在,但这应该没问题,dances(juliet) 应该 return 我是真的。相反,它 return 是真的,然后抛出一个关于舞者事实的异常。 有没有办法为不存在的事实或规则编写规则?我是否需要检查事实是否存在?
据我所知,没有办法使用不存在的谓词。您可以使用 this question 中描述的方法检查规则是否存在,或者您可以使用某种占位符来确保它 确实 存在。如果一条规则总是错误的,那么它似乎没有多大用处,所以在使用它之前写几个真实的案例。
dancer(someone). %% To make sure that fact exists
loves(romeo, juliet).
dances(juliet) :- loves(romeo, juliet).
dances(juliet) :- exists(dancer), dancer(juliet).
从技术上讲,您可以这样做:
dances(juliet) :- catch(dancer(juliet),
error(existence_error(procedure, dancer/1), _),
false
).
如果谓词存在,它将 运行 dancer(juliet)
,如果不存在则失败,否则会出错。
虽然我不会说这是一件非常明智的事情。
要实现 "failure if not existant",您可以使用指令 dynamic/1
.
声明谓词 dynamic
例如:
:- dynamic dancer/1.
如果将此指令添加到您的程序中,您将获得:
?- dances(X).
X = juliet .
没有错误。
我有一个事实:
loves(romeo, juliet).
然后我有一个 'or' 规则:
dances(juliet) :- loves(romeo, juliet).
dances(juliet) :- dancer(juliet).
如您所见,dancer 的事实并不存在,但这应该没问题,dances(juliet) 应该 return 我是真的。相反,它 return 是真的,然后抛出一个关于舞者事实的异常。 有没有办法为不存在的事实或规则编写规则?我是否需要检查事实是否存在?
据我所知,没有办法使用不存在的谓词。您可以使用 this question 中描述的方法检查规则是否存在,或者您可以使用某种占位符来确保它 确实 存在。如果一条规则总是错误的,那么它似乎没有多大用处,所以在使用它之前写几个真实的案例。
dancer(someone). %% To make sure that fact exists
loves(romeo, juliet).
dances(juliet) :- loves(romeo, juliet).
dances(juliet) :- exists(dancer), dancer(juliet).
从技术上讲,您可以这样做:
dances(juliet) :- catch(dancer(juliet),
error(existence_error(procedure, dancer/1), _),
false
).
如果谓词存在,它将 运行 dancer(juliet)
,如果不存在则失败,否则会出错。
虽然我不会说这是一件非常明智的事情。
要实现 "failure if not existant",您可以使用指令 dynamic/1
.
例如:
:- dynamic dancer/1.
如果将此指令添加到您的程序中,您将获得:
?- dances(X). X = juliet .
没有错误。