Comparing PROLOG input to facts

2019-08-24 03:35发布

问题:

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).

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),

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?

回答1:

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.

You express the fact that Author authoredAfter Year1 if there is a blog post written by Author in Year2 and Year2 >= Year1.


If you issue a query to see if author1 wrote anything after 2009:

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

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