【发布时间】:2022-11-17 20:57:13
【问题描述】:
我必须将一个元素插入到 2 的幂位置的列表中
例如在列表中
L = [1, 2, 3, 4, 5, 6, 7, 8]
我应该在 first 元素之后插入一个元素 E = 0,然后是 third,然后是 7th,等等,所以结果列表将是
R = [1, 0, 2, 3, 0, 4, 5, 6, 7, 0, 8]
我尝试使用预定义谓词 nth1/4 将元素添加到列表中的位置 P,然后通过将其乘以 2 来增加位置 P
%empty list
ins_aux(_, [], _, _, []).
%if the position is even, add the element and then multiply P by 2
%and add a value K which is incremented at every step to get the next position
ins_aux(E, L, P, K, Res) :- 0 is mod(P, 2), !,
nth1(P, Res, E, L),
P1 is (P*2)+K,
K1 is K+1,
ins_aux(E, Res, P1, K1, Res).
%if the position is odd, add the element to the list
ins_aux(E, L, P, K, Res) :- nth1(P, Res, E, L),
P1 is P+1,
ins_aux(E, Res, P1, K, Res).
我的问题是这总是输出false.我显然做错了什么只是我不知道是什么
【问题讨论】: