将PROLOG输入与事实进行比较

时间:2015-01-05 15:57:38

标签: prolog

说我有一份PROLOG事实清单,分别是博客文章,作者和写作年份:

blogpost('Title 1', 'author1' 2012).
blogpost('Title 2', 'author1', 2011). 
blogpost('Title 3', 'author1' 2010).
blogpost('Title 4', 'author1', 2006).
blogpost('Title 5', 'author2' 2009).
blogpost('Title 6', 'author2', 2011).

我想写一个有两个参数/输入的规则,作者和年份。如果输入的作者在指定年份之后写了一篇文章,PROLOG将返回true。 这是我尝试过的:

authoredAfter(X,Z) :-
    blogpost(_,X,Z),

因此,如果我查询?- authoredAfter('author1',2010). PROLOG将返回true,因为作者在2010年撰写了一篇文章。但是,如果我查询?- authoredAfter('author1',2009).,它将返回false,但我希望它返回true,因为author1在那一年之后写了一篇文章。

我的问题是,如何将用户输入值与事实中的值进行比较?

1 个答案:

答案 0 :(得分:0)

您需要两个使用两个不同的变量作为文章的年份和您想要开始搜索的年份并进行比较。像这样:

authoredAfter(Author, Year1):-
    blogpost(_, Author, Year2),
    Year2 >= Year1.

如果AuthorYear1中有Author撰写的博文,则表示Year2 已创作 Year2 >= Year1这一事实}。


如果您发出查询以查看 author1 是否在2009年之后写了任何内容:

?- authoredAfter(author1, 2009).
true ;
true ;
true ;
false.

目标满意三次,因为作者1在2009年(2010年,2011年,2012年)之后有3篇博文。如果您想获得一个答案,无论存在多少这样的文章,您都可以使用once/1

authoredAfter(Author, Year1):-
    once((blogpost(_, Author, Year2),
          Year2 >= Year1)).

?- authoredAfter(author1, 2009).
true.