Return Prolog 中两个函数的值相等

Return value of two functions are equal in Prolog

我有一个电影数据库,其中包含

movie(blood_simple, 1984).
movie(the_cotton_club, 1984).
movie(american_beauty, 1999).
...

我想编写一个函数,如果给定的两部电影在同一年上映,则 returns 为真,否则为假。

我在比较两个值时遇到问题,我的函数总是 returns false。

这是我的代码:

sameyear(Movie1,Movie2):-
    movie(Movie1,Year1),
    movie(Movie2,Year2).
    % here I tried comparing Year1 with Year2 like: Year1 == Year2, Year1 =:= Year2, nothing worked.
  

另一个代码:

sameyear(Movie1,Movie2):-
    movie(Movie1,Year1),
    movie(Movie2,Year1).    % here I expected that it would return true if the movies were released at the
 same year, because Year1 has already got a value at *movie(Movie1,Year1)*, but that didn't happen

你能帮帮我吗?

您在 movie(Movie2, Year2) 子句的末尾写了一个点 (.)。因此,这意味着您结束了谓词。如果你再写Year1 == Year2.,那么这是另一个规则。

因此您应该使用逗号,它在语义上接近 逻辑和:

sameyear(Movie1,Movie2):-
    movie(Movie1,Year1),
    movie(Movie2,Year2)<b>,</b>  % ← added a comma
    Year1 == Year2.

然后生成:

?- sameyear(M1, M2).
M1 = M2, M2 = blood_simple ;
M1 = blood_simple,
M2 = the_cotton_club ;
M1 = the_cotton_club,
M2 = blood_simple ;
M1 = M2, M2 = the_cotton_club ;
M1 = M2, M2 = american_beauty.