List 在Prolog中查找所有列表旋转

List 在Prolog中查找所有列表旋转,list,rotation,prolog,List,Rotation,Prolog,我试图在Prolog中产生所有可能的列表循环。以下是一个例子: rotate([1,2,3], X). X = [1,2,3]; X = [2,3,1]; X = [3,1,2]. 我找到了一个旋转的方法: rotate([H|T], R) :- append(T, [H], R). | ?- append(_Prefix, _Suffix, [1,2,3]), append(_Suffix, _Prefix, Rotation). Rotation = [1,2,3] ? ; R

我试图在Prolog中产生所有可能的列表循环。以下是一个例子:

rotate([1,2,3], X).
X = [1,2,3];
X = [2,3,1];
X = [3,1,2].
我找到了一个旋转的方法:

rotate([H|T], R) :-
    append(T, [H], R).
| ?- append(_Prefix, _Suffix, [1,2,3]), append(_Suffix, _Prefix, Rotation).

Rotation = [1,2,3] ? ;
Rotation = [2,3,1] ? ;
Rotation = [3,1,2] ? ;
Rotation = [1,2,3]
yes
但如何找到所有

答复
您可以使用
append/3
谓词将列表拆分为前缀和后缀。例如:

?- append(Prefix, Suffix, [1,2,3]).
Prefix = [],
Suffix = [1, 2, 3] ;
Prefix = [1],
Suffix = [2, 3] ;
Prefix = [1, 2],
Suffix = [3] ;
Prefix = [1, 2, 3],
Suffix = [] ;
false.
然后,将后缀附加到前缀后可以进行旋转:

rotate([H|T], R) :-
    append(T, [H], R).
| ?- append(_Prefix, _Suffix, [1,2,3]), append(_Suffix, _Prefix, Rotation).

Rotation = [1,2,3] ? ;
Rotation = [2,3,1] ? ;
Rotation = [3,1,2] ? ;
Rotation = [1,2,3]
yes

但有一个多余的解决方案。你能摆脱它吗?提示:如果前缀或后缀是空列表,您将获得原始列表。

谢谢,就这样。我已经为这个问题添加了一个解决方案(没有多余的解决方案)。你可以用
Right=[][\u124;|]
替换
Right\=[[]
,并将目标向前移动。