考虑到起始位置和长度,我想生成该长度的子列表。我使用累加器在下面做了:
get_sublist(_,_,0,Sublist,Sublist):-!.
get_sublist(List,Position,Length,Sublist,Acc):-
nth1(Position,List,Element),
append([Element],Acc,Acc1),
Position1 is Position + 1,
Length1 is Length - 1,
get_sublist(List,Position1,Length1,Sublist,Acc1).
通过使用更多内置谓词或使用替代方法,是否有更短/更快的方法?感谢。
答案 0 :(得分:3)
我会选择:
sublist(List, Offset, Length, Sublist):-
length(Prefix, Offset),
append(Prefix, Rest, List),
length(Sublist, Length),
append(Sublist, _, Rest).
使用示例:
?- sublist([a,b,c,d,e,f,g,h,i,j,k], 3, 6, X).
X = [d, e, f, g, h, i].
请注意,我在这里使用了{0}的Offset
参数。
答案 1 :(得分:0)
如果我运行你的代码,我会得到
?- get_sublist([a,b,c,d,e,f,g,h,i,j,k], 3, 6, X, []).
X = [h, g, f, e, d, c].
然后,反向/ 2缺失?在这种情况下,我会建议好旧的findall / 3:
get_sublist(List,Position,Length,Sublist):-
Stop is Position+Length-1,
findall(X, (between(Position,Stop,P),nth1(P,List,X)), Sublist).
编辑 bagof / 3,通过范围变量的声明(这里只是P),将避免findall引入的问题:
get_sublist(List,Position,Length,Sublist):-
Stop is Position+Length-1,
bagof(X, P^(between(Position,Stop,P),nth1(P,List,X)), Sublist).
?- get_sublist([A,B,C,D,E,F,G,H,I,J,K], 3, 6, X).
X = [C, D, E, F, G, H].