制作一个比较列表的谓词?

时间:2016-05-02 20:53:00

标签: prolog member

我对Prolog比较新,所以请耐心等待。假设我有事实,每个人都包含一个人,他们的爱好是什么(在列表中):

hobbies(mark, [running, video_games, soccer])
hobbies(jasmine, [writing, swimming, music])
hobbies(john, [rugby, rowing, pets, politics])
hobbies(lisa, [gymnastics, dancing, television])

我现在要做的是定义一个谓词(让我们称之为samesame(P1, P2, H)如果P1P2有爱好{{1}共同的。我知道我需要使用成员谓词,但到目前为止我只学会了如何在更简单的情况下使用它。它会是这样的:

H

但是我当然知道这是不可能的。如何在这些事实中访问列表?

1 个答案:

答案 0 :(得分:1)

您需要一个列表才能使用member谓词。因此,您必须获取P1P2的爱好列表。怎么做?使用hobbies事实

hobbies(mark, [running, video_games, soccer]).
hobbies(jasmine, [writing, swimming, music]).
hobbies(john, [rugby, rowing, pets, politics]).
hobbies(lisa, [gymnastics, dancing, television, video_games]).

same(P1, P2, H) :-
    % Hobbies1 is a list of hobbies of P1
    hobbies(P1, Hobbies1),
    member(H, Hobbies1),
    % Hobbies2 is a list of hobbies of P2
    hobbies(P2, Hobbies2),
    member(H, Hobbies2),
    % P1 and P2 are not the same. Also eliminates symmetrical redundancy
    P1 @< P2.

查询

?- same(P1, P2, H).
P1 = mark,
P2 = lisa,
H = video_games ;
false.