I scan
I scan

Reputation: 65

Prolog: How to get oldest and youngest in bloodline

Let's say that I have a bloodline of male population Williams and Skywalker families as my knowledge base:

father(phil,tom, williams).
father(tom, bob, williams).
father(bob, robert, williams).
father(robert, steve, williams).

father(anakin, luke, skywalker)
father(luke, finn, skywalker)
father(finn, andrew, skywalker)
father( andrew, charles, skywalker)

Which rule can I use to know the oldest and youngest in bloodline?

For example

?- oldestYoungest(skywalker,X,Y)

should return

X = anakin
Y = charles

Upvotes: 3

Views: 612

Answers (1)

mcansado
mcansado

Reputation: 2164

This works with your Knowledge Base (KB) looking the way it does now.

youngest(LastName, Son) :-
    father(_, Son, LastName),
    \+father(Son, _, LastName).

oldest(LastName, Father) :-
    father(Father, _, LastName),
    \+father(_, Father, LastName).

oldestYoungest(LastName, Oldest, Youngest) :-
    youngest(LastName, Youngest),
    oldest(LastName, Oldest).

You should note that Prolog variables are upper-case and constants (or facts) are lower-case.

Technically, this answer finds oldest as the person with no father in the KB and the youngest and the person with no son in the KB. It works because your KB is defined that way.

Upvotes: 4

Related Questions