codiearcher
codiearcher

Reputation: 403

Add to the front of a list, the same element which is found at the end of the list

I am trying to learn Prolog but finding it very difficult. I am having trouble adding an element which is found at the end of a list, to the front of the list. So far all I can manage to do is to remove the element and put it at the front, however, I don't want to remove it, I want it to stay at the back plus add an instance of it to the front.

I have tried reviewing similar questions but I am still stuck.

I know I am going about it the wrong way, but here is what I have so far:

addLastToFront([], []).
addLastToFront(L, [H|T]) :- append(T, [H], L).

Which produces:

 ?- addLastToFront([a,b,c,d], X) --> ([d,a,b,c])

What I am trying to do:

?- addLastToFront([a,b,c,d], X) --> ([d,a,b,c,d])

Upvotes: 1

Views: 67

Answers (2)

lurker
lurker

Reputation: 58244

SWI Prolog has a last(L, X) which succeeds if X is the last element of L.

Armed with that predicate, you can easily define your needed predicate last_as_first(L, [X|L]) to be [X|L] is the list formed from the last element of list L used also as the head if X is the last element of L. Which written in Prolog is:

last_as_first(L, [X|L]) :- last(L, X).

If you want to use append/3, you can define last(L, X) as append(_, [X], L).

last_as_first(L, [X|L]) :- append(_, [X], L).

Upvotes: 1

user27815
user27815

Reputation: 4797

list([])     --> [].
list([L|Ls]) --> [L], list(Ls).

concatenation([]) --> [].
concatenation([List|Lists]) -->
        list(List),
        concatenation(Lists).

You can use this DCG from https://www.metalevel.at/prolog/dcg and then query:

?-List1 =[a,b,c],phrase(concatenation([Front,[Last]]),List1),List2 = [Last|List1].
Front = [a, b],
Last = c,
List1 = [a, b, c],
List2 = [c, a, b, c];

Upvotes: 0

Related Questions