2010-12-23 37 views
4

假設我在familyTree.pl文件下面的代碼:查詢在兩個人之間的關係的Prolog的家譜

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。但;當已知關係類型的數量超過幾個和/或給定兩個人之間存在鏈式關係(即:Lisa和Emily:Lisa是Emily的男朋友的母親)時,這個解決方案似乎浪費時間。

回答

4

我想出了這個解決方案(未選中徹底,但它似乎是確定):

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' ; 
+0

嗨。你可以看看[這](http://stackoverflow.com/questions/32770849/given-values-x-and-y-return-rule-name-if-it-is-true?noredirect=1#請評論533381490_32770849)? – Pranav 2015-09-24 21:42:31