James Verdune
James Verdune

Reputation: 101

Prolog: How come this loop doesn't work?

I just started learning prolog recently and am confused about how the recursion works. I have written this code:

test(X,B):- B is X + 2, B < 22, test(B,_).
test(X,Y).

I want it to return 20 or 21, but instead, if I call, say, test(4,X) it returns 6 over and over again (7 times to be exact), like this:

X = 6 ;
X = 6 ;
X = 6 ;
...

etc. So I was wondering what I was doing wrong. Thanks in advance for the help! Really appreciate it.

Upvotes: 1

Views: 45

Answers (1)

false
false

Reputation: 10102

You misinterpreted the result you got, look:

?-  test(4,X).
   X = 6
;  X = 6
;  X = 6
;  X = 6
;  X = 6
;  X = 6
;  X = 6
;  X = 6
;  true.   % <==== 

Note the true at the end, it means: Yes, this is true for any X!

Here is what you probably meant to write - trying to simulate your exact way of expression:

mtest(X0, X) :-
   X1 is X0+2,
   X1 < 22,
   mtest(X1, X).
mtest(X0, X) :-
   X is X0,
   X+2 >= 22.

Some things are remarkable:

  • Note variable X in the first clause: It "hands back" the result.

  • The second clause needs to express the opposite of the very condition you gave in the first clause, because clauses are read independently of each other. In your original program the fact test(X,Y). stated that the relation is true for everything! (You got a warning for that, didn't you?) For example, also test(7,1000). succeeded.

  • The X is X0 is here to ensure that the second argument will be only a number but not an expression.

In any case, as a beginner, try to use library(clpfd), instead of (is)/2. Or even better, start with .

Upvotes: 2

Related Questions