I’m trying to write a program in Prolog, which will insert an element into a certain position, so e.g.
?- ins(a, [1,2,3,4,5], 3, X).
X = [1,2,a,3,4,5].
I have the following code:
ins(X,[H|T],P,OUT) :-
length([T3],P),
concatenate(X,[H],T),
ins(...).
The problem is that it is inserting element X in given index from back (I even know where the problem is -> the length([T3],P) which is obviously the length of the list from back not from head) . I was trying to remember how much elements did I cut off and insert X when “number of cut off elements” = P, but I can’t really write that in Prolog. Any ideas?
The predicate fails if Pos = 0 or Pos > length(List) + 1