查询Prolog家谱中两个人的关系 [英] Query the relation between two people in a Prolog Family Tree
问题描述
假设我的 familyTree.pl 文件中有以下代码:
Suppose I have the below code in my familyTree.pl file:
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)).
现在,我想得到以下问题的答案:
Now, I want to get the answer to the questions like:
What is the relationship between Tom and Bob ?
What is the relationship between Lisa and Emily ?
我该如何问以上问题来进行序言?
我能想出的唯一解决方案是迭代已知的关系类型(汤姆、鲍勃)或(丽莎、艾米丽)作为参数并检查哪个返回 true.但;这个解决方案似乎是在浪费时间,当已知关系类型的数量不止几个和/或给定的两个人之间存在连锁关系时(即:丽莎和艾米丽:丽莎是艾米丽男朋友的母亲).
The only solution I could come up with was to iterate over the known relation types giving (Tom, Bob) or (Lisa, Emily) as paremeter and check which one returns true. But; this solution seems to be a waste of time, when the number of known relation types are more than a few and/or there is a chain relation between the given two people (i.e.: Lisa and Emily: Lisa is Emily's boyfriend's mother).
推荐答案
我想出了这个解决方案(没有彻底检查但似乎没问题):
I have come up with this solution (not checked thoroughly but it seems to be ok):
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家谱中两个人的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!