Adam Duvall
Adam Duvall

Reputation: 111

Prolog: Move last element in list to front

Is there some built in predicate or easy way to move the last element in a list to the front? The only way I've come up with is a predicate that stores the last element, deletes it from the original list, and then doing append(Last Elem, Original List, New List) which is a bit cumbersome.

Upvotes: 0

Views: 1180

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

I don't know if there are any built-in predicate, but this can be achieve with very simple code:

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

Upvotes: 3

Related Questions