Search code examples
prolog

Prolog:Testing 2 lists for similarity


How can the elements of two different lists be checked for equality? Without, the first and the last entry. Unfortunately my approach does not work and unfortunately I cannot find my mistake.

isNearlyEqual(L1,L2) :-
    drop(L1,0,LA1),size(L1,X),drop(L1,X,LA1),
    drop(L2,0,LA2),size(L2,Y),drop(L2,Y,LA2),
    size(LA1,size1).
% My idea is now to check the 2 fragments of the list for equality. But I don't know how at the moment.
% First he removes the first and the last element.
% Then he should check the list for equality.
    
drop(Xs,N,Rs) :-
  integer(N),
  N > 0,
  drop(Xs,1,N,Rs).

drop( []     , _ , _ , [] ) .
drop( [X|Xs] , P , N , Rs ) :-
  ( 0 =:= P mod N -> R1 = Rs ; [X|R1] = Rs ) ,
  P1 is P+1 ,
  drop(Xs,P1,N,R1).
  
  
size([],0).

size([_|T],N):-
    size(T,M),
    N is M+1.

size_sub([],[]).

size_sub([H|T],[N|T2]):-
    size(H,N),
    size_sub(T,T2).

Solution

  • You defined the condition

        N > 0
    

    in your drop/3 predicate, but also you are trying to do

        drop(L1,0,LA1)
    

    so the predicate is always false

    As I understand your problem, try this solution

        isNearlyEqual([_|T],[_|T2]) :-
            removeLast(T,L1),
            removeLast(T2,L2),
            completeEqual(L1, L2).
    
        completeEqual([],[]).
        completeEqual([H|T], [H2|T2]):-
            completeEqual(T,T2),
            H == H2.
    
        removeLast([_],[]).
        removeLast([H|[H2|T2]], Z):-
            removeLast([H2|T2],Z1),
            append([H],Z1,Z).