Prolog中两个元组列表的交集

时间:2014-03-10 21:26:52

标签: list prolog

我试图使用intersection()函数在Prolog中找到两个列表的交集。不幸的是,我的代码给出了不良结果。

这就是我所拥有的:

RESULTA = [ ('10:00 am - 11:15 am', 'TR'), ('6:00 pm - 8:50 pm', 'T'), ('6:00 pm - 8:50 pm', 'R'), ('6:00 pm - 8:50 pm', 'M')].

RESULTB = [ ('6:00 pm - 8:50 pm', 'R'), ('3:00 pm - 3:50 pm', 'TR')].

intersection(RESULTA, RESULTB, AB).

所需的输出为('6:00 pm - 8:50 pm', 'R')但是,代码返回RESULTA = AB, AB = [].

有没有人知道如何解决这个问题?

修改

RESULTA和RESULTB实际上是从bagof()操作生成的。我的实际代码是:

1 ?- bagof((TIME, DAYS), COURSE^teaches_at('Dr. J. Leidig', COURSE, TIME, DAYS), RESULTA).
RESULTA = [ ('10:00 am - 11:15 am', 'TR'), ('6:00 pm - 8:50 pm', 'T'), ('6:00 pm - 8:50 pm', 'R'), ('6:00 pm - 8:50 pm', 'M')].

2 ?- bagof((TIME, DAYS), COURSE^teaches_at('Dr. El-Said', COURSE, TIME, DAYS), RESULTB).
RESULTB = [ ('6:00 pm - 8:50 pm', 'R'), ('3:00 pm - 3:50 pm', 'TR')

很抱歉这个混乱。

2 个答案:

答案 0 :(得分:1)

您问题中的代码实际上是对Prolog的查询。

有3种不同的查询:每个查询都以句点结尾。所有三个查询都是完全独立的,即使它们共享具有相同名称的变量。

要执行您想要的操作,只需将句点更改为逗号:

RESULTA = [ ('10:00 am - 11:15 am', 'TR'), ('6:00 pm - 8:50 pm', 'T'), ('6:00 pm - 8:50 pm', 'R'), ('6:00 pm - 8:50 pm', 'M')],
RESULTB = [ ('6:00 pm - 8:50 pm', 'R'), ('3:00 pm - 3:50 pm', 'TR')],
intersection(RESULTA, RESULTB, AB).

更新问题后更新:

bagof((TIME, DAYS), COURSE^teaches_at('Dr. J. Leidig', COURSE, TIME, DAYS), RESULTA),
bagof((TIME, DAYS), COURSE^teaches_at('Dr. El-Said', COURSE, TIME, DAYS), RESULTB),
intersection(RESULTA, RESULTB, AB).

答案 1 :(得分:0)

您必须在规则中使用这些变量,例如

test(AB) :-
    RESULTA = [ ('10:00 am - 11:15 am', 'TR'), ('6:00 pm - 8:50 pm', 'T'), ('6:00 pm - 8:50 pm', 'R'), ('6:00 pm - 8:50 pm', 'M')],
    RESULTB = [ ('6:00 pm - 8:50 pm', 'R'), ('3:00 pm - 3:50 pm', 'TR')],
    intersection(RESULTA, RESULTB, AB).

然后查阅该文件。你会得到

?- test(AB).
AB = [ ('6:00 pm - 8:50 pm', 'R')].