从列表中删除第 N 个元素并将其值显示在变量中

Drop out the N-th element from a list and display its value in a variable

我有一个谓词 drop_at(X, L, N, R) 应该删除第 N 个元素 X 来自列表 L。变量X绑定到第N个元素的值, R 被实例化到结果列表。

例如:

?− drop_at(X, [a, b, c, d], 2, R).
X = b
R = [a, c, d]

我如何实现既丢弃元素又将其绑定到变量 X?

现在我可以使用这个删除第 n 个元素:

drop([],_,[],_).
drop([_|Xs],N,Ys,1) :- 
    drop(Xs,N,Ys,N).
drop([X|Xs],N,[X|Ys],K) :- 
    K > 1, 
    K1 is K - 1, 
    drop(Xs,N,Ys,K1).

但是它删除了每个 N 个元素,这不是我想要的。

经过更多尝试,我得到了这个:

drop(1,[_|T],T).
drop(P,[X|Y],[X|R]):-
    P1 is P-1,
    drop(P1,Y,R).

但这仍然不是我想要的。

drop_at(_, [], _, []).     % list is empty, nothing to do
drop_at(H, [H|T], 1, T).   % we've found the right item
drop_at(X, [H|T], N, [H|T2]) :-  % not there yet, recurse
  N > 1,
  N2 is N - 1,
  drop_at(X, T, N2, T2).