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!

'fail' predicate confusion

Status
Not open for further replies.

everlonggg

Programmer
Joined
Dec 6, 2008
Messages
4
Location
CA
The fail predicate seems a bit unpredictable under certain cases to me. Take the following example.

Code:
a(1).
a(2).
b(3).
b(4).
go:- a(X), write(X).
go:- a(X), write(X), b(Y), write(Y).


Query this with ?- go, fail.

The result is 12134234. How does this make sense? Can somebody explain the logic behind that? Thanks.
 
you wrote "go, fail."

you have 2 rules for go.

the first rule is executed ==> 1
fail
Prolog searches for the last point of choice : fact with a
the first rule is executed ==> 2
fail
the first rule is no longer avalaible (only 2 facts with a).
the second rule is executed ==> 1, 3
fail
the second rule is executed at the last point of choice : fact with b ==> 4
fail
the second rule is executed at the last point of choice : fact with a because all the choices for b have been explored ==> 2
etc, etc.

 
the second rule is executed at the last point of choice : fact with b ==> 4
fail"

This step does not make logical sense to me. Why would this not print 2, 4?
 
After 13 you would have 24 ?
No, because Prolog starts from the end of the rule to search back the last point of choice.
 
Sorry, 14. That was a mistake on my behalf.

So what you're saying is that the fail predicate doesn't make it start the whole second rule over again, but only checks for a new b(Y)?
 
Yes backtrack search from the last point of choice at b(Y).
 
Gotcha! And in the way it works in recursive list cases... let's make up an example.

f([], 0).
f([H|T], X):- f(T, Y), g(H,Z), X is Y+Z.
g(a, 1).
g(X, 0).

inputting f([a,b,a],X), write(X), fail. to this will give you something like...
2110. It will get the first 2, fail. go back and instead of satisfying g(a, 1), satisfy g(X, 0). Then we get a 1. Fail. Now where would it traverse from there?

Thanks! I think I'm starting to catch onto this.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top