gpt4 book ai didi

list - 从列表中删除每个第 n 个元素的 Prolog 程序

转载 作者:行者123 更新时间:2023-12-04 22:20:45 24 4
gpt4 key购买 nike

你能帮我解决以下问题吗?

Write a ternary predicate delete_nth that deletes every n-th element from a list.



示例运行:
?‐ delete_nth([a,b,c,d,e,f],2,L).
L = [a, c, e] ;
false
?‐ delete_nth([a,b,c,d,e,f],1,L).
L = [] ;
false
?‐ delete_nth([a,b,c,d,e,f],0,L).
false

我试过这个:
listnum([],0).
listnum([_|L],N) :-
listnum(L,N1),
N is N1+1.

delete_nth([],_,_).
delete_nth([X|L],C,L1) :-
listnum(L,S),
Num is S+1,
( C>0
-> Y is round(Num/C),Y=0
-> delete_nth(L,C,L1)
; delete_nth(L,C,[X|L1])
).

最佳答案

我有点奢侈的变体:

delete_nth(L, N, R) :-
N > 0, % Added to conform "?‐ delete_nth([a,b,c,d,e,f],0,L). false"
( N1 is N - 1, length(Begin, N1), append(Begin, [_|Rest], L) ->
delete_nth(Rest, N, RestNew), append(Begin, RestNew, R)
;
R = L
).

关于list - 从列表中删除每个第 n 个元素的 Prolog 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23439360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com