2010-12-23 2 views
4

내 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)를 paremeter로 제공하는 알려진 관계 유형을 반복하고 어느 것이 true를 반환하는지 확인하는 것이 었습니다. 그러나; 이 해결책은 알려진 관계 유형의 수가 적고 주어진 두 사람 사이에 연쇄 관계가있는 시간 낭비로 보인다 (예 : Lisa and 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

안녕하세요. [this] (http://stackoverflow.com/questions/32770849/given-values-x-and-y-return-rule-name-if-it-is-true?noredirect=1#)에서 살펴볼 수 있습니까? comment53381490_32770849) 제발? – Pranav

+0

장면 뒤에서 일어나는 일을 설명 할 수 있습니까? 현재의 대답은 예상되는 결과를 제공하지만 이해하기가 어렵습니다. –