1

Below is the given program to print if a list is palindrome or not but I am not able to use condition L1=L & L1<>L for printing "List is Palindrome!" & "List is not palindrome", By the way I almost tried every way available online for doing it but to no avail was it a success.

I tried (if -> then ; else) & (if , then);(else , then) and many more but all resulted in failure. Your help is highly appreciated!

domains
    ll=integer*
predicates
    rev(ll,ll).
    revl(ll,ll,ll).
clauses
    rev(L1,L):-
        revl(L1,[],L).
% I want to use if and else here to print If it is palindrome or not!

    revl([],L,L).
    revl([H|L1],L2,L3):-
        revl(L1,[H|L2],L3).
false
  • 10,264
  • 13
  • 101
  • 209

1 Answers1

0

You don't need to use if and else.

If execution reaches the point you indicate, you definitely have a palindrome.

rev(L1,L):-
    revl(L1,[],L),       % it's a palindrome if revl(L1,[],L) succeeds
    write("It's a palindrome!").

% Recursively reverse A to B in revl(A,B,X)

revl([],L,L).                            % succeed if at the end B=X 
revl([H|L1],L2,L3):- revl(L1,[H|L2],L3). % reverse 1 step

What you want:

rev(L1,L):-
    revl(L1,[],L),!    % it's a palindrome if revl(L1,[],L) succeeds
    write("It's a palindrome!").

rev(_,_):-             % alternative solution in case it's not a palindrome   
    write("It's not a palindrome!").

% Recursively reverse A to B in revl(A,B,X)

revl([],L,L).                            % succeed if at the end B=X 
revl([H|L1],L2,L3):- revl(L1,[H|L2],L3). % reverse 1 step

Using if-then-else

rev(L1,L):-
    revl(L1,[],L) 
    -> write("It's a palindrome!")
    ;  write("It's not a palindrome!").

revl([],L,L).
revl([H|L1],L2,L3):- revl(L1,[H|L2],L3).
David Tonhofer
  • 14,559
  • 5
  • 55
  • 51
  • Yes, I know I don't need to use If then else but I want to use If then else but it is not working in PROLOG!! By the way I already have completed the program with and without concatation but still thanks for seeing my problem and trying to help me, I really appreciate your efforts but I am not able to use if then else in my PROLOG and that's why I want to do it with If then else only. – Faizan Shaikh Sarkar Apr 28 '20 at 10:37
  • @FaizanShaikhSarkar Added an if-then-else version. Does it work? – David Tonhofer Apr 28 '20 at 11:50