比较 PROLOG 输入和事实 [英] Comparing PROLOG input to facts
问题描述
假设我有一个 PROLOG 事实列表,其中包括博客文章标题、作者和撰写年份:
Say I have a list of PROLOG facts, which are Blog Post titles, the author, and the year they were written:
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
.这是我尝试过的:
I want to write a rule which has two parameters/inputs, the author, and the year. If the author entered has written an article after the specified year, PROLOG would return true
.
Here is what I have tried:
authoredAfter(X,Z) :-
blogpost(_,X,Z),
所以如果我查询 ?- authoredAfter('author1',2010).
PROLOG 会返回 true
因为作者在 2010 年写了一篇文章.但是,如果我查询 ?- authoredAfter('author1',2009).
,它会返回 false
,但我希望它返回 true
因为 author1 已经写了那年之后的一篇文章.
So if I queried ?- authoredAfter('author1',2010).
PROLOG would return true
because the Author has written an article in 2010. However, if I query ?- authoredAfter('author1',2009).
, it would return false
, but I want it to return true
because author1 has written an article after that year.
我的问题是,如何将用户输入的值与事实中的值进行比较?
My question is, how do I compare the user input value to the value in the fact?
推荐答案
您需要使用两个不同的变量来表示文章的年份和要开始搜索的年份并比较它们.像这样:
You need two use two distinct variables for the year of the article and for the year you want to start your search from and compare them. Something like this:
authoredAfter(Author, Year1):-
blogpost(_, Author, Year2),
Year2 >= Year1.
如果在 Author
中有一篇由 Author
撰写的博客文章,您表示 Author
authoredAfter Year1
code>Year2 和 Year2 >= Year1
.
You express the fact that Author
authoredAfter Year1
if there is a blog post written by Author
in Year2
and Year2 >= Year1
.
如果您发出查询以查看 author1 是否在 2009 年之后写了任何内容:
If you issue a query to see if author1 wrote anything after 2009:
?- authoredAfter(author1, 2009).
true ;
true ;
true ;
false.
3 次达到目标,因为 author1 在 2009 年之后有 3 篇博文(2010、2011、2012).如果你想得到一个单一的答案,不管有多少这样的文章,你都可以使用once/1
:
the goal is satisfied three times as author1 has 3 blog posts after 2009 (2010, 2011, 2012). If you want to get a single answer, no matter how many such articles exist, you can use once/1
:
authoredAfter(Author, Year1):-
once((blogpost(_, Author, Year2),
Year2 >= Year1)).
?- authoredAfter(author1, 2009).
true.
这篇关于比较 PROLOG 输入和事实的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!