您可以使用append
拆分列表,以及length
创建列表:
% rotate(+List, +N, -RotatedList)
% True when RotatedList is List rotated N positions to the right
rotate(List, N, RotatedList) :-
length(Back, N), % create a list of variables of length N
append(Front, Back, List), % split L
append(Back, Front, RotatedList).
注意:这仅适用于 N
为清楚起见进行编辑该谓词定义为List and N调用谓词时,参数不是变量。我无意中重新排序了您原来问题中的参数,因为在 Prolog 中,约定是严格输入参数应位于输出参数之前。所以,List and N和输入参数,旋转列表是一个输出参数。所以这些是正确的查询:
?- rotate([a,b,c], 2, R).
?- rotate([a,b,c], 1, [c,a,b]).
但是这个:
?- rotate(L, 2, [a,b,c]).
找到一个答案后就会进入无限递归。
阅读 SWI-Prolog 文档时,请留意标有“?”的谓词参数,如length。它们可以如本例所示使用。