Prolog Type Error

前端 未结 4 877
面向向阳花
面向向阳花 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:30

    Prolog doesn't do inline expression evaluation. Thus, calls such as trim(L2, Length/2 , B) and trim(L, round(Length/2), A) will not work as you expect. Expressions are only evaluated in specific when using certain operators such as is/2, arithmetic comparisons, or their CLP(FD) counterparts. These expressions would need to be done as: L is Length // 2, trim(L2, L, B) and R is round(Length/2), trim(L, R, A) if done literally.

    Your solution could be condensed, however, as follows.

    swap(L, S) :-
        same_length(L, S),               % L and S are necessarily the same length
        length(L, N),
        M is N // 2,   % integer divide ; half the original list length
        length(Left, M),                 % Left is a list of half the length of L
                                         %   or half minus one if the length is odd
        (   (N mod 2) =:= 1              % If the original length is odd...
        ->  append(Left, [H|Right], L),  % then L is Left + [H|Right]
            append(Right, [H|Left], S)   %   So, S is Right + [H|Left]
        ;   append(Left, Right, L),      % otherwise, L is Left + Right
            append(Right, Left, S)       %   So, S is Right + Left
        ).
    

提交回复
热议问题