Prolog 'fail' predicate.

C4f6bdabaa3fc338779a568bff36a1f2
0
everlonggg 101 Dec 07, 2008 at 01:45

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.

8 Replies

Please log in or register to post a reply.

2b97deded6213469bcd87b65cce5d014
0
Mihail121 102 Dec 07, 2008 at 09:14

OMG, it’s not the result, it’s just SWI printing stuff as it moves along the search tree :). Try it without ‘fail’ and check out the 6 models you get.

C4f6bdabaa3fc338779a568bff36a1f2
0
everlonggg 101 Dec 07, 2008 at 16:27

@Mihail121

OMG, it’s not the result, it’s just SWI printing stuff as it moves along the search tree :). Try it without ‘fail’ and check out the 6 models you get.

First of all, thanks for your reply :)

I realize it’s just printing stuff as it moves along. However, the way it reaches things is beyond my understanding. Namely, when it reaches the single “4” instead of “2, 4”. Any explanation of this?

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Dec 07, 2008 at 17:09

It’s very logical though. There are two go’s, one with a single a(X), and one with an a(X) followed by a b(Y).

So the first two digits, 1 and 2, are simply all combinations that can be made with a. The following digits, 134234, are from the second go, which are all combinations with a and b combined. First it combines a(1) with b(Y), resulting in 134, then it does the same for a(2), resulting in 234.

C4f6bdabaa3fc338779a568bff36a1f2
0
everlonggg 101 Dec 07, 2008 at 17:26

@.oisyn

The following digits, 134234, are from the second go, which are all combinations with a and b combined. First it combines a(1) with b(Y), resulting in 134, then it does the same for a(2), resulting in 234.

Would this not work in the manner of “13”, followed by “24”? This is the approach I imagine it should have taken. I apparently misunderstand something in the way prolog processes these

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Dec 07, 2008 at 17:54

No, because there are four possible combinations: a(1)b(3), a(1)b(4), a(2)b(3) and a(2)b(4). So for every a(X), it needs to check every b(Y)

C4f6bdabaa3fc338779a568bff36a1f2
0
everlonggg 101 Dec 07, 2008 at 17:56

Oh! So does the fail predicate not make you start the whole rule over again? It solely checks for the last call and backtracks that?

340bf64ac6abda6e40f7e860279823cb
0
_oisyn 101 Dec 07, 2008 at 18:06

Note that I’m not a prolog guru whatsoever, but yes I think that’s true :). Which makes sense btw, because if it backtracked the whole searchtree up until the root, it has to start all over again.

C4f6bdabaa3fc338779a568bff36a1f2
0
everlonggg 101 Dec 07, 2008 at 18:07

Wow, that clears a LOT up. Thanks a bunch for your help!