如何在序言中指定一个唯一的事实?

How to specify an unique fact in prolog?

我想指定一个人对某事的评论是正面的还是负面的,但不能同时是两者。

我想将一般规则和这些事实放入我的文件中:

:-comment(Person, Thing, B), comment(Person, Thing, OtherB), B \=OtherB.
comment(person, book, positive).
comment(person, book, negative).

当我尝试进行查询时,我会收到一个错误,或者告诉我某些事情是矛盾的。

以下事实当然有效:

comment(person, book, positive).
comment(person, icecream, negativa).

你应该在你的文件中添加一个checkContradictory(至少在gnuprolog)以下方式:

yourfile.lp

comment(person, book, positive).
comment(person, book, negative).

checkContradictory:- checkCommentContradiction, ... others checking predicates

checkCommentContradiction:-comment(Person, Thing, positive),
            comment(Person, Thing, negative),throw(contradiction_with_comments).

所以如果你想在查询之前检查你的文件,只需执行你的 checkContradictory 或者如果你有一个主谓词,只需添加 checkContradictory 喜欢的要求。

重要如果你需要一个没有错误的yes和一个有矛盾的Exception你需要添加一个findall:

yourfile.lp

comment(person, book, positive).
comment(person, book, negative).

checkFreeOfContradictory:- checkAllCommentsContradictions.

checkAllCommentsContradictions:-findall(X,checkCommentContradiction,R).

checkCommentContradiction:-comment(Person, Thing, B1),
            comment(Person, Thing, B2),
            (B1==B2->true;throw(contradiction_with_comments)).

主要是因为同一个事实会统一到comment(Person, thing, B1)comment(Person, Thing, B2) .

如果你重构你的谓词会不会更容易? 以这样的方式用两个谓词替换一个谓词:

positive_comment(Person,Book).
negative_comment(Person,Book).

然后使用类似的东西

positive_comment(Person,Book):-
negative_comment(Person,Book),
throw_some_error,
false.
negative_comment(Person,Book):-
positive_comment(Person,Book),
throw_some_error,
false.

或更好地使用单独的检查器:

check_comments_consistency(Person,Book):-
  positive_comment(Person,Book),
  negative_comment(Person,Book),
  throw_some_error.

...或类似的东西。

你明白了吗?