Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Prolog "little" issue

Status
Not open for further replies.

Kirdneh

Programmer
Joined
Jan 19, 2013
Messages
2
Hi,

I am learning prolog and I am not able to fullfill the following excercise:

1. I have a list of facts:
f(name0).
m(name1).
-> these are persons, f(x) means female, m(x) means male.
child_of(x,y).
-->x is a child of y.

2. I want to now if x is and descendent of y:
descendent(x,y) :- child_of(x,y).
descendent(x,y) :- descendent(x,z), child_of(z,y).

3. so far everything worked fine, but here is my problem:
I want to have a request descendent(x, y, z) which means that
x is a descendent of y and z is the realtion between them.

so if I am requesting:
?- descendent(person1, person2, X).
X = c(person2).
Which means person1 is a child of person 2.
or
?- descendent(person3, person4, X).
X = c(c(person4)).
Which means person 3 is a child of a child of person4.

How can I code that? Any hints would be a pleasure.
 
The design for descendent/2, is almost good : try descendent(name1, name0) and after the answer true type ";" instead of Enter, you will enter an infinite loop !
After having fixed the bug, try the same design for descendent/3.
 
I do not get this...

So what I want as output is:
?- descendent(person3, person4, X).
X = c(c(person4)).

so if person3 is a descendent of person4 I can count all the c()
to know how much generations are between the two persons.

with my code I only know if a person is descendent of
another person and this works quite well.

Is it possible to genereate an output like this?!
I am really not sure because I can not find a tutorial
which deals with such a topic...
 
Well here is my code, works with SWI-Prolog
Code:
child_of(name1,name0).
child_of(name2,name1).
child_of(name3,name2).


descendent(X,Y) :-
	child_of(X,Y).
descendent(X,Y) :-
	child_of(Z,Y),
	descendent(X,Z).
If I use
Code:
descendent(X,Y) :-
	descendent(X,Z),
	child_of(Z,Y).
at the query descendent(name1, X). I get name0, and after pressing <space> (or ";") I get a loop.

For descendent/3, its exactly the same thing :
Code:
descendent(X, Y, c(Y)) :-
	child_of(X,Y).

descendent(X, Y, c(T)) :-
	child_of(X,Z),
	descendent(Z,Y, T).
with answer :
?- descendent(name3, name0, X).
X = c(c(c(name0))) ;
false.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top