简体   繁体   中英

why do you define a rule twice in prolog

follows(A, B, Seen) :- not_member(B, Seen); isFriendsWith(A, B).
follows(A, B, Seen) :- isFriendsWith(A, X), not_member(X, Seen), follows(X, B, [X|Seen]).

Why is the same rule defined twice. When you run the query if the first rule is true. Does it resolve.

This in a way is at the heart of how Prolog's resolution process.

Say you define the rule as above in your question, plus, a few facts:

isFriendsWith(john,mary).
isFriendsWith(mary,peter).

And then query

?- follows(john, Who, []);

The first rule is tried first (because it's first) and returns:

Who = mary

because the isFriendsWith fact matches X to mary.

But you're not happy, so you ask for more answers by entering

;

which causes Prolog to backtrack . In effect Prolog is going to retrace its steps, looking for alternative facts and rules. Here there's no other fact about john being friend with anyone, so the first rule has failed.

The second rule kicks in and Prolog tries to prove (after pattern matching):

isFriendsWith(john, X),
not_member(X, []),
follows(X, B, [X]).

it finds a fact (again, but it's applying a new rule) that X=mary, which is not in the empty list, then goes off to prove

follows(mary, B, [mary])

Which does have a solution as mary is friends with peter, and so the system has proven a second result and answers:

Who = mary

If you ask more proofs at this point, the system backtracks again and seeks more applications of the rules. With just these two facts there are none, and so the system answers

no

and returns.

Overall, your two rules result in the system identifying recursively all the 'follow' paths through the 'isFriendsWith' graph. The list Seen is there to ensure that it doesn't follow cyclical paths which would cause it to loop indefinitely.

If you find this example confusing, look up examples of backtracking in Prolog first. It is essential to its theorem prover and you will not understand any of Prolog without it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM