I have started using Prolog and I am having this problem with a dynamic predicate - I don't get the right result.
This is my database:
:- dynamic mother/2.
mother(X,Y).
grandemother(X,Y) :-
mother(X,A),
mother(A,Y).
These are some of the results I get:
1 ?- assert(mother(alice,lise)).
true.
2 ?- assert(mother(lise,kate)).
true.
3 ?- grandemother(alice,X). % should only give X = kate.
true ;
X = lise ;
X = kate ;
true ;
X = kate.
4 ?- grandemother(alice,lise). % should only give false.
true ;
true ;
true ;
false.
5 ?- grandemother(X,kate). % should only give X = alice.
true ;
true ;
X = alice ;
X = alice ;
X = lise.
I really don't know where the problem is, any ideas?
As @lurker said in his comment, the issue is your line
mother(X,Y).
, directly after the dynamic declaration.To break down exactly what's happening, I'll look at
grandemother(alice,X)
(after your asserts ofmother(alice,lise)
andmother(lise,kate)
):Therefore,
grandemother(alice,X)
succeeds without having to bind X.We ask again, and this time:
grandemother(alice,X)
succeeds with X bound to lise. Ask again...X is kate. Again...
X is unbound again, so we just get
true
. Again...X is kate again. Any more?
So we get no more results.
The solution, as @lurker pointed out, is to remove
mother(X,Y).
, so that this unbound behaviour cannot occur.