Today's post is about the detection of a palindrome using Prolog. A palindrome is defined as some word that can be read from start to end or end to start and it will not change. For example, the word ANNA is a palindrome.
Now, using the idea that a palindromic word is a word that can be read back and forth and does not change, we come with the following ...
Let X be some word. If X is the empty word then it is a palindrome. If X is not the empty word then let Y be the reverse of X. If Y equals X, X is a palindromic word. Instead of focussing on words, we focus on lists.
%palin/1 X is a palindrome
palin([]).
palin(X) :- revList(X, Y), X = Y.
A more succinct version of the above would avoid the additional test of equality, i.e. lead to the following predicate:
palin(X) :- revList(X, X).
Which clearly is the the same, i.e. if reversing X leads to X, then clearly, X has to be palindromic. revList is a binary predicate that takes a list as input and outputs the reverse list.
No comments:
Post a Comment