xiamtos
xiamtos

Reputation: 69

Prolog - syngeneic lists

Two lists are syngeneic if have the same length and all the elements are the same except first and last. I have managed to do the comparisons between the lengths but how to see if the elements is the same except first and last of two lists.
Here is my code:

sug([H|T],[H1|T1]) :-
   length([H|T],N),
   length([H1|T1],M),
   N==M.

e.x. of what is syngeneic list -> sug([a,b,c,d],[d,b,c,a])

Upvotes: 0

Views: 49

Answers (3)

joel76
joel76

Reputation: 5675

Why not, in SWI-Prolog :

sug(L1, L2) :-
    append([[_], Ls, [_]], L1),
    append([[_], Ls, [_]], L2).

Upvotes: 0

gusbro
gusbro

Reputation: 22585

Assumming there has to be at least two elements on the lists (so that they differ in each corresponding list), you can use append/3 to match the intermediate list and check that the first and last differ:

sug([HL|LTail], [HR|RTail]):-
  HL \= HR,
  append(L, [LL], LTail),
  append(L, [LR], RTail),
  LL \= LR.

If first and last item does not need to be different (may or may not) then the procedure would just look:

sug([_|LTail], [_|RTail]):-
  append(L, [_], LTail),
  append(L, [_], RTail).

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You can do it with several rules:

  1. Empty lists are syngeneic
  2. Lists are syngeneic when their tails are the same except for possibly the last element
  3. Empty lists are the same
  4. Lists with only one element are the same for the purposes of rule 2
  5. Lists are the same for the purpose of rule 2 if their heads match and their tails are the same for the purpose of rule 2.

There is no need to check the length explicitly, because the rules above would never match two lists with different number of elements.

Here is how the above rules can be coded in Prolog - essentially, there is a line-for-line match:

sug([], []).
sug([_|T1], [_|T2]) :- sameExceptLast(T1, T2).
sameExceptLast([], []).
sameExceptLast([_], [_]).
sameExceptLast([X|T1], [X|T2]) :- sameExceptLast(T1, T2).

Here is a demo on ideone.

Upvotes: 1

Related Questions