list length, inserting element
list, prolog
Solution
% ins(Val,List,Pos,Res)
ins(Val,[H|List],Pos,[H|Res]):- Pos > 1, !,
Pos1 is Pos - 1, ins(Val,List,Pos1,Res).
ins(Val, List, 1, [Val|List]).
The predicate fails if Pos = 0 or Pos > length(List) + 1
Problem
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?