I am trying to create a Palindrome Programme on Visual Prolog that checks user input number. I somehow wrote some codes BUT it shows error and it is difficult for me to remove errors. Please, I need help on this code.
DOMAINS Num,Temp,Reverse=integer
PREDICATES palindrome
CLAUSES *
palindrome:-
Reverse=:=0,
write("Enter a number to check ."),
readint(Number),
Temp=Number
loop(Temp=/=0) :-
Reverse=Reverse*10,
Reverse=Reverse+ Temp mod 10,
Temp=Temp/10,
false.
(Number=:=Reverse->
write("The Number ",Number," is a Palindrome "),
fail ; Number=/=Reverse->
write("The Number ",Number," is not a Palindrome.") ; .
GOAL palindrome.
In writing a prolog program, it can be helpful to write down a clear, specific problem statement and decompose the problem. Something like:
That leads us to this interface predicate which pretty much recapitulates the problem statement, thus:
Now, all we have to do is figure out how to reverse the digits of a number. Given that we've eliminated dealing with the sign, above, it's easy: Strip digits from the right end, adding them to the left end of the result, until we hit zero.
A useful idiom in prolog is to have a public predicate that fronts a private workder predicate that often takes an accumulator wherein the final result is built up as you recursively work the problem. Also, in this case (and many others), there is usually a general case and one or a few special cases. Here, our special case, which terminates the compuation is when the source value is zero.
Which leads us to this definition of "how to reverse the digits of a number":
Another approach, of course, would be to convert the number into a string (which is a list of individual characters), reverse that list using the built-in
reverse/2
predicate and unify that with the original value. I doubt that is what your instructor is looking for, however.