Using the mechanism repeat
that @Enigmativity showed in his answer is probably the better way to implement this, rather than recursion. However, your recursive method would basically work except for a particular issue (and one suggestion):
You are trying to re-instantiate a variable in your second clause, which Prolog will not allow. So if the user queries, guess_num(9).
you attempt to read(X)
when X = 9
, which will fail unless the user enters 9
again. You need to use a new variable.
Using a cut (!
) in this kind of method will eliminate the choice point that will occur if the user guesses correctly. Without the cut, once the user is told they have the right answer, Prolog will prompt the user for more solutions.
Making the above corrections would give you:
guess_num(10) :-
!,
write("You have guessed right"), nl.
guess_num(X) :-
X =\= 10,
write("Wrong guess"), nl,
read(X1),
guess_num(X1).
Using the above code:
?- guess_num(9).
Wrong guess
|: 8.
Wrong guess
|: 10.
You have guessed right
true.
?-
Without the cut:
?- guess_num(9).
Wrong guess
|: 8.
Wrong guess
|: 10.
You have guessed right
true ;
false.
?-