PROLOG program: write_descendant_chain. Later chapters examine the special predi
ID: 669313 • Letter: P
Question
PROLOG program:
write_descendant_chain. Later chapters examine the special predicates write and nl, which can be used to produce output other than just the values of variables. For example, if there is a clause
write_child(X,Y) :write(X), write(’ is a child of ’), write(Y), nl. then the query write_child(john_smith,sue_jones) will always succeed and will also print
john_smith is a child of sue_jones on one line.
Include this predicate in your program, and write the clauses for a predicate write_descendant_chain(x,y) that prints a chain from x to y when x is a descendant of y but prints nothing when x is not a descendant of y. For example, if John Smith is a descendant of William Brown, then write_descendant_chain(john_smith,william_brown) should print a sequence of lines something like this:
john_smith is a child of sue_jones
sue_jones is a child of harvey_jones
harvey_jones is a child of davy_jones
davy_jones is a child of anna_brown
anna_brown is a child of william_brown
Hint: You will not be able to use the descendant predicate you dened for this. Use the child predicate together with write_child. Also, work down from y rather than up from x.
Explanation / Answer
Descendant_chain(X, Y) : descendant(X, Y) :- parent(X, Y). descendant(X, Y) :- parent(X, Z), descendant(Z, Y). parent(bob, tim). parent(joe, bob). parent(joe, mary). descendant(X, Y) :- parent(X, Y). descendant(X, Y) :- parent(X, Z), descendant(Z, Y). descendants(X, L) :- findall(A, descendant(X, A), L).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.