1

i have a to write a routine which lists all descendants so far i wrote

descend(X,Y) :- child(X,Y). 
descend(X,Y) :- child(X,Z), descend(Z,Y).

which works fine so any descendent i need to find i just do descend(X,name). and it keeps giving me descendants of name in form of X= descend1, X = descend2 but to get the results i have to press ; every time what i am trying is to write is a routine descendb which gives the list of all descends without pressing ;

descendb(X) :- descend(A,X), write(A).

this is obviously wrong.

4

1 回答 1

1

You can get all results with a 'failure driven' loop, aka forall/2

descendb(X) :- forall(descend(A,X), writeln(A)).

That's generally useful only when we have to do some 'side effect' on every solution found, like writeln (for instance) does. Since you say you're after 'the list of all descends', try findall/3 instead:

descendb(X, Ds) :- findall(D, descend(D,X), Ds).

Since we have 2 arguments, you are not obliged to make a choice, descendb/1 and descendb/2 are effectively different predicates.

于 2013-11-06T06:35:34.500 回答