简体   繁体   English

Prolog中两个元组列表的交集

[英]Intersection of Two Lists of Tuples in Prolog

I am trying to find the intersection of two lists in Prolog using the intersection() function. 我正在尝试使用intersection()函数在Prolog中找到两个列表的intersection() Unfortunately, my code is giving undesirable results. 不幸的是,我的代码给出了不良的结果。

Here is what I have: 这是我所拥有的:

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

The desired output is ('6:00 pm - 8:50 pm', 'R') however, the code returns RESULTA = AB, AB = []. 所需的输出是('6:00 pm - 8:50 pm', 'R')但是,代码返回RESULTA = AB, AB = [].

Does anyone have an idea on how to fix this issue? 有谁知道如何解决此问题?

EDIT 编辑

RESULTA and RESULTB are actually generated from bagof() operations. RESULTA和RESULTB实际上是从bagof()操作生成的。 My actual code is: 我的实际代码是:

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

Sorry for the confusion. 对困惑感到抱歉。

The code in your question is really queries to Prolog. 您问题中的代码实际上是对Prolog的查询。

There are 3 different queries: each query ends with a period. 有3个不同的查询:每个查询以一个句点结尾。 All three queries are completely independent, even if they share variables with same names. 这三个查询都是完全独立的,即使它们共享相同名称的变量也是如此。

To do what you want just change periods to commas: 要执行您想要的操作,只需将句点更改为逗号即可:

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

Update after the question updated: 问题更新后更新:

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

you must use that variables in a rule, like 您必须在规则中使用该变量,例如

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

then consult the file. 然后查阅文件。 The you'll get 你会得到

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM