Good job on the prime testing. Your loop, however, is both more code than you need and kind of off-track. Based on the code sample you show, you probably want this:
generatePrime(X, Y, N) :-
between(X, Y, N),
isPrime(N).
See how this works?
?- generatePrime(2, 10, X).
X = 2 ;
X = 3 ;
X = 5 ;
X = 7 ;
false.
Those ;
are interactively given by the human operator.
If you want to print all of them out, you could go with a classic failure driven loop like so:
generatePrime(X, Y) :-
between(X, Y, N),
isPrime(N),
write(N), nl,
fail.
generatePrime(_, _).
I wouldn't recommend this, but failure-driven loops seem to be a hot topic for beginners for some reason. I'd be more inclined to do something like this:
generatePrimes(X, Y) :-
forall(
(between(X, Y, N), isPrime(N)),
(write(N), nl))).
Either way you're basically there, and you have a lot of options.
Now, a few special notes:
isPrime(2).
is basically equivalent to what you have withisPrime(2) :- true, !.
I would recommend staying away from the cut while you're just getting started. And you almost never really need an explicittrue
.not/1
is not ISO. Use\+/2
instead (i.e.\+ divisible(X, 2)
)X is 1
is no better thanX = 1
.is/2
is only necessary if you have an expression on the right-hand side you want evaluated and stored in the variable named on the left-hand-side. Other calling conventions foris/2
either don't work or aren't productive.X is X+1
will always fail. Prolog has variables, not assignables. You cannot change the value of a variable ever. You can only arrange for a binding somewhere else to have a particular value, perhaps recursively. In this case, the right thing to do isX1 is X+1, generatePrime(Y, X1)
. Most, but not all, expected uses of assignment can be handled similarly to this.- I am skeptical that
isPrime(X) -> write(X) ; true
will do the right thing without being surrounded by parentheses; this is an area of Prolog's syntax that usually trips me up, so I almost always wind up parenthesizing the whole conditional expression to get it right. Also, I don't think you need; true
on there.