1

in prolog I have my database set up like this

male("John").
male("Bob").
male("Billy").
male("Gary").

Parent("Bob","John").
Parent("Billy","Bob").
Parent("Gary", "Billy").


ancestor(Ancestor, Descendant) :-
    parent(Ancestor, Descendant).
ancestor(Ancestor, Descendant) :-
    parent(Ancestor, CommonAncestor),
    ancestor(CommonAncestor, Descendant).

Would it be possible to track how far into recursion this ancestor function went? for example if we ran

?- ancestor("Billy", "John", X).

Would it be possible to have X return 2, or in the case of

?- ancestor("Bob", "John", X).

have X return 1?

1 Answer 1

2

Yo could write:

ancestor(Ancestor, Descendant,1) :-
    parent(Ancestor, Descendant).
ancestor(Ancestor, Descendant,X) :-
    parent(Ancestor, CommonAncestor),
    ancestor(CommonAncestor, Descendant,X1),
    X is X1+1.

Some examples:

?- ancestor("Billy", "John", X).
X = 2 ;
false.

?- ancestor("Bob", "John", X).
X = 1 ;
false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.