2012-01-23 2 views
2

주어진 사람이 두 번째 조상의 조상인지 확인하는 작은 프롤로그 프로그램을 작성해야합니다. 사람이 다른 사람의 조상 인 경우프롤로그와 조상의 관계

mother(tim, anna). 
mother(anna, fanny). 
mother(daniel, fanny). 
mother(celine, gertrude). 
father(tim, bernd). 
father(anna, ephraim). 
father(daniel, ephraim). 
father(celine, daniel). 

parent(X,Y) :- mother(X,Y). 
parent(X,Y) :- father(X,Y). 

테스트 쉽습니다 : 이이 사실과 규칙이

ancestor(X, Y) :- parent(X, Y). 
ancestor(X, Y) :- parent(X, Z), ancestor(Z, Y). 

하지만 지금은 (X, Y를하는 방법의 조상을 작성해야, Z)는 두 사람 사이의 관계를 인쇄합니다. 이 모양은 다음과 같아야합니다.

?- ancestor(ephraim, tim, X). 
false. 
?- ancestor(tim, ephraim, X). 
X = father(mother(tim)). 

그리고 이것이 문제입니다. 어떻게해야 할 지 모르겠습니다.

답변

1

당신은 @Scott 헌터의 솔루션을 적용하는 어큐뮬레이터를 사용할 수 있습니다

mother(anna, fanny). 
mother(daniel, fanny). 
mother(celine, gertrude). 
father(tim, bernd). 
father(anna, ephraim). 
father(daniel, ephraim). 
father(celine, daniel). 

ancestor(X, Y, Z) :- ancestor(X, Y, X, Z). 
ancestor(X, Y, Acc, father(Acc)) :- father(X, Y). 
ancestor(X, Y, Acc, mother(Acc)) :- mother(X, Y). 
ancestor(X, Y, Acc, Result) :- 
    father(X, Z), 
    ancestor(Z, Y, father(Acc), Result). 
ancestor(X, Y, Acc, Result) :- 
    mother(X, Z), 
    ancestor(Z, Y, mother(Acc), Result). 

편집 : 스콧 헌터 (Scott Hunter)가 편집에서 보여 주었 듯이 여기에 명시 적 누적 기가 필요하지 않습니다. 각 반복에서 용어의 안쪽 부분을 쉽게 언 바운드 할 수 있기 때문입니다. 그러므로 그의 해결책은 더 좋습니다!

+0

"Adapt": "수정"이라고 말하는 정중 한 방법입니다. –

0

간단하게 부모의 종류는 각 단계에서 사용되는 어떤 책자 용어를 추가 (적절한 순서로 결과를 얻기 위해 편집) :

ancestor(X,Y,father(X)) :- father(X,Y). 
ancestor(X,Y,mother(X)) :- mother(X,Y). 
ancestor(X,Y,father(Z2)) :- father(Z,Y), ancestor(X,Z,Z2). 
ancestor(X,Y,mother(Z2)) :- mother(Z,Y), ancestor(X,Z,Z2). 
+0

:

parent(X, Y, mother(X)) :- mother(X, Y). parent(X, Y, father(X)) :- father(X, Y). ancestor(X, Y, R) :- parent(X, Y, R). ancestor(X, Y, R) :- parent(X, Z, P), ancestor(Z, Y, A), eldest(A, P, R). eldest(A, P, R) :- A =.. [Af, Aa], ( atom(Aa) -> T = P ; eldest(Aa, P, T) ), R =.. [Af, T]. 

테스트, 나는 팀 아버지 만든 엑스). 어머니 (아버지 (안나))를 반환합니다. 나는 그것을 고치려고했지만 나는 그것을 얻지 못한다. – user1164180

0

@Mog에 의해 어큐뮬레이터 tecnique에 대한 용어의 조작 대안 : 조상 (팀, 에브라임 : 꽤 잘 불행히도 father(ugo, tim).

?- ancestor(tim, ephraim, X). 
X = father(mother(tim)) . 

?- ancestor(ugo, ephraim, X). 
X = father(mother(father(ugo))) . 
관련 문제