让我们使用 clpfd!出于通用性和其他许多好的原因:
:- use_module(library(clpfd)).
我们基于
if_/3
和
(#>=)/3
定义
delete_nth/3
函数:
delete_nth(Xs,N,Ys) :-
N #> 0,
every_tmp_nth_deleted(Xs,0,N,Ys).
every_tmp_nth_deleted([] ,_ ,_,[] ).
every_tmp_nth_deleted([X|Xs],N0,N,Ys0) :-
N1 is N0+1,
if_(N1 #>= N,
(N2 = 0, Ys0 = Ys ),
(N2 = N1, Ys0 = [X|Ys])),
every_tmp_nth_deleted(Xs,N2,N,Ys).
示例查询:
?- delete_nth([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],2,Ys)。
Ys = [1,3,5,7,9,11,13,15] %成功确定性地
好的,那么再来点更一般化的东西怎么样?
?- delete_nth([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
N,Ys).
当 N = 1 时, Ys = []
; 当 N = 2 时, Ys = [1, 3, 5, 7, 9, 11, 13, 15]
; 当 N = 3 时, Ys = [1,2, 4,5, 7,8, 10,11, 13,14 ]
; 当 N = 4 时, Ys = [1,2,3, 5,6,7, 9,10,11, 13,14,15]
; 当 N = 5 时, Ys = [1,2,3,4, 6,7,8,9, 11,12,13,14 ]
; 当 N = 6 时, Ys = [1,2,3,4,5, 7,8,9,10,11, 13,14,15]
; 当 N = 7 时, Ys = [1,2,3,4,5,6, 8,9,10,11,12,13, 15]
; 当 N = 8 时, Ys = [1,2,3,4,5,6,7, 9,10,11,12,13,14,15]
; 当 N = 9 时, Ys = [1,2,3,4,5,6,7,8, 10,11,12,13,14,15]
; 当 N = 10 时, Ys = [1,2,3,4,5,6,7,8,9, 11,12,13,14,15]
; 当 N = 11 时, Ys = [1,2,3,4,5,6,7,8,9,10, 12,13,14,15]
; 当 N = 12 时, Ys = [1,2,3,4,5,6,7,8,9,10,11, 13,14,15]
; 当 N = 13 时, Ys = [1,2,3,4,5,6,7,8,9,10,11,12, 14,15]
; 当 N = 14 时, Ys = [1,2,3,4,5,6,7,8,9,10,11,12,13, 15]
; 当 N = 15 时, Ys = [1,2,3,4,5,6,7,8,9,10,11,12,13,14 ]
; 当 N > 15 时, Ys = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].
?‐ delete_nth([a,b,c,d,e,f],0,L).
这个问题的解决方案中出了什么问题吗?”我运行了查询,但没有看到重复的地方,但我想我可能理解错了你的意思。我是不是放错位置了剪切符?另外,如果你愿意,我想知道从递增计数到递减计数的优势是什么。谢谢! - Shon