yfdgvf asdasdas
yfdgvf asdasdas

Reputation: 170

Reverse the last two elements of a list in Prolog

I am trying to write the following predicate in Prolog while not making use of append/3:

lastTwoReversed(List, ListOf2)

which succeeds exactly when ListOf2 contains the last and the second-to-last elements of List in that order (i.e. reversed).

However, I don't know where to start. Any help is appreciated.

Upvotes: 3

Views: 971

Answers (3)

SND
SND

Reputation: 1557

You can write a simple recursive predicate with a base case pattern matching on a list consisting of two elements like so:

last_two_reversed([X,Y],[Y,X]).

Since this is probably homework, I think it's best if you try to write the recursive clause yourself.

Upvotes: 4

Fatalize
Fatalize

Reputation: 3543

Simply use the built-in predicate reverse/2:

last_two_reversed([A,B|T],[Y,X]) :-
    reverse([A,B|T],[Y,X|_]).

This will fail for lists with strictly less than two elements. A sensible thing to do would be to make it succeed using those two additional rules:

last_two_reversed([],[]).
last_two_reversed([H],[H]).

Upvotes: 3

coder
coder

Reputation: 12972

First of all, the predicate should fail or succeed with empty list or list with only one element??
In mathematical logic the predicate should return true with empty list and one-element list, because there are no last and second to-last elements to reverse.

So if you want to succeed with empty or one element list you should first start with :

  lastTwoReversed([],[]).
  lastTwoReversed([X],[X]).

(else don't write the above rules). Next as base you should write:

lastTwoReversed([X,Y],[Y,X]).

and finally for list of length 3 or greater:

lastTwoReversed([X,Y,Z|T],[X|T1]):-lastTwoReversed([Y,Z|T],T1).

Keep in mind that we write [X,Y,Z|T] to specify for list with 3 or more elements so that doesn't match the previous rules.

Upvotes: 1

Related Questions