gpt4 book ai didi

prolog - 查询Prolog家谱中两个人的关系

转载 作者:行者123 更新时间:2023-12-04 20:22:51 26 4
gpt4 key购买 nike

假设我的 familyTree.pl 文件中有以下代码:

male(tom).
male(bob).

female(lisa).
female(emily).

parent(tom, bob).
parent(lisa, bob).

morethanfriends(emily, bob).

father(X,Y) :- male(X), parent(X,Y).
mother(X,Y) :- female(X), parent(X,Y).
girlfriend(X,Y) :- female(X), (morethanfriends(X,Y); morethanfriends(Y,X)).
boyfriend(X,Y) :- male(X), (morethanfriends(X,Y); morethanfriends(Y,X)).

现在,我想得到以下问题的答案:
What is the relationship between Tom and Bob ?

What is the relationship between Lisa and Emily ?

我怎样才能问上述问题来进行序言?

我能想出的唯一解决方案是迭代已知的关系类型,将 (Tom, Bob) 或 (Lisa, Emily) 作为参数并检查哪个返回 true。但;这个解决方案似乎是在浪费时间,当已知关系类型的数量不止几个和/或给定的两个人之间存在链式关系(即:丽莎和艾米丽:丽莎是艾米丽男 friend 的母亲)。

最佳答案

我想出了这个解决方案(没有彻底检查,但似乎没问题):

relations(What, Name1, Name2):-
relation_facts(Facts, Name1, _),
relations1(Facts, [], Name2, What1),
atomic_list_concat(What1, What).

relations1(Facts, Forbidden, Name2, What):-
member(Relation, Facts),
call(Relation),
relations2(Relation, Forbidden, Name2, What).

relations2(Relation, Forbidden, Right, [Left, ' ', is, ' ', Right, '''s ', Name]):-
Relation =.. [Name, Left, Right],
Forbidden \= Right.
relations2(Relation, Forbidden, Name2, [Left, ' ', is, ' '| What]):-
Relation =.. [Name, Left, Right],
relation_facts(Facts, Right, _),
Forbidden\=Right,
relations1(Facts, Left, Name2, [_,_,_,_, NRight|What1]),
append([NRight|What1], ['''s ', Name], What).

% Here goes the relations you want to check for:
relation_facts([father(X,Y), mother(X,Y), girlfriend(X,Y), boyfriend(X,Y)], X, Y).

测试用例:
?- relations(Relation,lisa,emily).
Relation = 'lisa is emily\'s boyfriend\'s mother' ;

?- relations(Relation,lisa,bob).
Relation = 'lisa is bob\'s mother' ;

?- relations(Relation,_,_).
Relation = 'tom is bob\'s father' ;
Relation = 'tom is emily\'s boyfriend\'s father' ;
Relation = 'lisa is bob\'s mother' ;
Relation = 'lisa is emily\'s boyfriend\'s mother' ;
Relation = 'emily is bob\'s girlfriend' ;
Relation = 'bob is emily\'s boyfriend' ;

关于prolog - 查询Prolog家谱中两个人的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4518040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com