1

下面是打印列表是否为回文的给定程序,但我无法使用条件 L1=L & L1<>L 打印“列表为回文!” &“列表不是回文”,顺便说一句,我几乎尝试了所有在线可用的方法,但无济于事。

我尝试了 (if -> then ; else) & (if , then);(else , then) 等等,但都以失败告终。非常感谢您的帮助!

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

1 回答 1

0

你不需要使用 if 和 else。

如果执行达到您指定的点,那么您肯定有回文。

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

你想要什么:

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

使用 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).
于 2020-04-28T06:49:40.790 回答