Prolog Type Error

前端 未结 4 891
面向向阳花
面向向阳花 2021-01-27 07:23

I\'m working on a prolog algorithm that will perform a \"swap\" on a list.

Example:

Input: [1,2,3,4] -> Output: [3,4,1,2] Input: [1,2,3,4,5] -> Output: [4,5,3,1

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-27 07:49

    Here's another solution that is based upon a modification to a predicate posted by @joel76 for splitting a list into two equal length lists. The modification I made enables the predicate to succeed with an odd-length list by including the "middle" list of 0 or 1 elements as an argument. It also uses same_length to constrain the arguments to avoid a termination issue for certain arguments. I included a simple implementation of same_length/2 which not all Prologs have (it is included with SWI Prolog).

    swap(L, S) :-
        same_length(L, S),
        div(L, Front, Middle, Back),     % L is divided into two halfs & middle
        append(Back, Middle, NewFront),  % S is Back + Middle + Front
        append(NewFront, Front, S).
    
    % List L consists of Left + Middle + Right where Left and Right are equal length
    %   and Middle has maximum length of 1
    %
    div(L, Left, Middle, Right) :-
        split(L, L, Left, Middle, Right).
    
    split(L, [], [], [], L).
    split([H|T], [_], [], [H], T).
    split([H|T], [_, _|T1], [H|T2], M, Right) :-
        split(T, T1, T2, M, Right).
    
    % same_length/2 is pre-defined in SWI Prolog and succeeds if the arguments
    % are lists of equal length
    %
    same_length([], []).
    same_length([_|Xs], [_|Ys]) :- same_length(Xs, Ys).
    

提交回复
热议问题