How to program with prolog using lists for reversing

Viewed 51

We want now to evaluate if any word in our language which is only made with the letters {a,b}, is a palindrome or not. I did code the program below, but I want it to accept only letters a or letters b and none other, if we input any other letters then it’s false. Example : [a,b,a] is correct, [b,a,b] is correct but [b,b,a] or [a,b,a,b] is incorrect.

Here is what I tried to do, but I just want prolog to return true if the word is a palindrome with only the letters a or b and not any other letters. I hope someone will help me.

reverse(X,Y) :- reverse(X,[],Y).

reverse([],X,X).
reverse([X|Y],Z,T) :- reverse(Y,[X|Z],T).

langage6([]).

langage6(L):-
  reverse(L, L).
2 Answers

You need to check, whether the word is over the alphabet? In this case, this could be a solution:

langage6(L):-
    word_in_alphabet(L),
    reverse(L, L).


word_in_alphabet([]).
word_in_alphabet([a|Xs]) :- word_in_alphabet(Xs).
word_in_alphabet([b|Xs]) :- word_in_alphabet(Xs).

I'd just include a test for the letters while having the elements at hand:

letter(a).
letter(b).

reverseletter([],X,X).
reverseletter([X|Y],Z,T) :-
    letter(X), 
    reverseletter(Y,[X|Z],T).

langage6(L):-
  reverseletter(L, [], L).

Tested with SWISH:

?- langage6([a,b,a]).
true.

?- langage6([b,a,b]).
true.

?- langage6([b,b,a]).
false.

?- langage6([b,a,b,a]).
false.

This code can be used as a generator as well:

?- langage6(L).
L = []
L = [a]
L = [b]
L = [a, a]
L = [b, b]
L = [a, a, a]
L = [a, b, a]
L = [b, a, b]
L = [b, b, b]
L = [a, a, a, a]
L = [a, b, b, a]
...
Related