Prolog reverse front members of a list

Viewed 44

In Prolog i have to reverse a part of a List given the number (member of the list) until which the list is reversed. For example:

?- reverse_front(2,[3,2,4,1,5,6],L). L=[2,3,4,1,5,6]

The list before number 2 (inluding 2) is reversed and then appended to the remaining list...

?- reverse_front(4,[9,3,2,4,1,5],L). L = [4,2,3,9,1,5]

?- reverse_front(1,[3,2,4,1,6,5],L). L = [1,4,2,3,6,5]

The solution can be done using reverse/2 and append/3.

Do you have any idea how that can be done?

1 Answers

Yes, you can use reverse/2 and append/3 to achieve that.

Something like this:

reverse_front(Item, List, NList):-
  append(L1, [Item|L2], List),
  reverse(L1, RL1),
  append([Item|RL1], L2, NList).

Sample run:

?- reverse_front(4,[9,3,2,4,1,5],L).
L = [4, 2, 3, 9, 1, 5] ;
false.

?- reverse_front(1,[3,2,4,1,6,5],L).
L = [1, 4, 2, 3, 6, 5] ;
false.
Related