Search code examples
prologdcg

Prolog: Swap first and last elements in list


I'm trying to write a program that swaps the 1st and last elements.

The function takes 2 parameters. A list and a variable that's displayed as the newly swapped list.

I thought I was doing it the lazy way, but it's turning out to be just as hard for me.

I was going to grab the head, put it aside -- grab the last element of the tail, put it aside -- take the tail, remove the last element, put it aside also, then append all 3 together to make a list

I'm having trouble removing the last element of the tail.

I have something like this:

swap( [H|T],  Y ) :-

  % GET HEAD, LAST OF TAIL, AND TAIL WITH LAST ELEM REMOVED

  % GET HEAD (NEW LAST ELEMENT)

   H = NEW_LASTELEMENT,

  % GET LAST ELEMENT (LAST OF TAIL, WILL BE NEW HEAD)

   last(T,X), X = NEWHEAD, 

  % CUT END OF TAIL OFF

   cutlast(T, Z), REST OF CODE . . .

  .



% CUT LAST
cutlast([H | T], [H | T2]) :- T = [_|_], cutlast(T, T2).

I borrowed the cutlast predicate from the web, but I'm not sure how it's even supposed to work. I've been test passing parameters to it for an hour now and they all keep returning false. Any assistance is appreciated.


Solution

  • Could be just:

    swap(A, B) :-
        append([First | Mid], [Last], A),
        append([Last | Mid], [First], B).
    

    Additional facts to succeed with one element and empty lists, if it's needed:

    swap([X], [X]).
    swap([], []).