Prolog Question - Square number
I have written a set of two predicates to test whether a number is a square number.
patrat_perfect(A):- patr(A, 0).
patr(A, S):- A =:= S * S.
patr(A,S):- A > S * S, T is S+1, patrat(A, T).
patr(A,S):- A < S * S, fail.
The first predicate, patrat_perfect
simply execute a call for the second predicate with the value 0 for the second parameter, and the number which should be tested whether or not it is a perfect square for the first parameter.
The patr
predicate practically searches that number S
from 0
to sqrt(A)
, which respects the equation S * S = A
. In order to do so, the predicate increases the value of S
with 1
if A > S * S
. If at the next call, A = S * S
, then the predicate returns true
and if A < S * S
, then the predicate r开发者_Python百科eturns false
through the call of the built-in predicate fail
.
The problem is that at every call of the patrat_perfect
predicate, I receive the false value. Could you please tell me where do I go wrong?
When I fixed a typo in your code (you're calling patrat
, but don't define it), it seems to work correctly (see http://ideone.com/j7fSA and http://ideone.com/SjIws).
Maybe you have copied the code incorrectly, or you have patrat
defined somewhere else, which works differently.
精彩评论