Sunday, October 27, 2013

Prolog: Insert an element on a given position

%Insert an element onto the n-th position of a list.
domains
element=integer
list=element*

predicates
insert(list, element, integer, integer, list)

clauses
%If initial list is empty(no elements in the list and CurrentPosition is still 1 because it was not incremented)
insert([], Element, InsertionPosition, 1, [Element]).

%We reached the moment in which the initial list is empty, but CurrentPosition is not 1(case handled above)
insert([], Element, InsertionPosition, CurrentPosition, []).

%Reached the case in which CurrentPosition is equal to InsertionPosition so we ll insert the element!
insert(List, Element, InsertionPosition, InsertionPosition, [Element| ResultedListTail]):-
CurrentPositionCopy = InsertionPosition + 1,
insert(List, Element, InsertionPosition, CurrentPositionCopy, ResultedListTail).

%By default we should copy element from initial list to resulted list and increment currentPosition
insert([Head| Tail], Element, InsertionPosition, CurrentPosition, [Head| ResultedListTail]):-
CurrentPositionCopy = CurrentPosition + 1,
insert(Tail, Element, InsertionPosition, CurrentPositionCopy, ResultedListTail).


goal
%We will insert element 2 on position 2
insert([1, 3, 4, 5, 6, 7], 2, 2, 1, ResultedList),
write(ResultedList).