Smiley Flower
Smiley Flower

Reputation: 100

Ensure Input List Minimum Length Prolog

I have a predicate that is true when two lists are identitcal, save that their first and last elements are swapped.

A requirement, however is that the predicate is UNTRUE when there are < 2 elements in the input List.

swap_ends([], []).
swap_ends(L1, L2) :-
   append([H1 | B1], [H2], L1),
   append([H2 | B1], [H1], L2).

This is correct for all instances where |inputList| >= 2, but also yields things like.

swap_ends([12345],L).

L = [-1231].

But we would expect no value for L.

I have tried substituting:

swap_ends([], []).

for

   swap_ends([A], [A]).

But this ends with an obvious fail state for some cases.

Upvotes: 2

Views: 111

Answers (1)

Paulo Moura
Paulo Moura

Reputation: 18683

A simple solution reusing your code is:

swap_ends([X1, X2| Xs], [Y1, Y2| Ys]) :-
    swap_ends_aux([X1, X2| Xs], [Y1, Y2| Ys])

swap_ends_aux([], []).
swap_ends_aux(L1, L2) :-
    append([H1| B1], [H2], L1),
    append([H2| B1], [H1], L2).

Upvotes: 2

Related Questions