How to use if then else condition in DOSBOX TurboProlog

381 Views Asked by At

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).
1

There are 1 best solutions below

2
David Tonhofer On

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).