Prolog为什么这里有重做?

时间:2015-09-29 12:52:27

标签: recursion prolog

所以,我有这段代码:

shuffle([],[],[]).
shuffle([], Shuffled, Rest):-
    listReverse(Rest, RestRes),
    shuffle(RestRes, Shuffled, []).
shuffle([A|[]], [A|Shuffled], Rest):-
    shuffle(Rest, Shuffled, []).
shuffle([A, B|List], [A|Shuffled], Rest):-
    shuffle(List, Shuffled, [B|Rest]).

帮助者:

listReverse(L, R):-
    listReverse(L,[],R).
listReverse([H|T],A,R):-    
    listReverse(T,[H|A],R).  
listReverse([],A,A).

当我打电话时,它工作正常:

shuffle([1,2,3], X, []),

我得到:X = [1,3,2]但是后面有一个问号“?”,如果我按下“;”,那么prolog重做声明,设置X = [1,3,2]并再次返回相同的内容,结束了。

为什么会这样,我该如何解决?

看起来像这样:

X = [1,3,2,4] ? ;
     77   64  Redo: skyffla([1,2,3,4],[1,3,2,4]) ? 
     78   65  Redo: shuffle([1,2,3,4],[1,3,2,4],[]) ? 
     79   66  Redo: shuffle([3,4],[3,2,4],[2]) ? 
     80   67  Redo: shuffle([],[2,4],[4,2]) ? 
     85   68  Redo: shuffle([2,4],[2,4],[]) ? 
     86   69  Redo: shuffle([],[4],[4]) ? 
     90   70  Redo: shuffle([4],[4],[]) ? 
     91   71  Redo: shuffle([],[],[]) ? 
     92   72  Call: listReverse([],_2668) ? 
     93   73  Call: listReverse([],[],_2693) ? 
     93   73  Exit: listReverse([],[],[]) ? 
     92   72  Exit: listReverse([],[]) ? 
     94   72  Call: shuffle([],_2604,[]) ? 
     94   72  Exit: shuffle([],[],[]) ? 
     91   71  Exit: shuffle([],[],[]) ? 
     90   70  Exit: shuffle([4],[4],[]) ? 
     86   69  Exit: shuffle([],[4],[4]) ? 
     85   68  Exit: shuffle([2,4],[2,4],[]) ? 
     80   67  Exit: shuffle([],[2,4],[4,2]) ? 
     79   66  Exit: shuffle([3,4],[3,2,4],[2]) ? 
     78   65  Exit: shuffle([1,2,3,4],[1,3,2,4],[]) ? 
     77   64  Exit: skyffla([1,2,3,4],[1,3,2,4]) ? 

X = [1,3,2,4] ? ;

1 个答案:

答案 0 :(得分:0)

以下程序怎么样?

shuffle([], Shuffled, Shuffled).

shuffle( List, [X | Shuffled], Rest):-

    list_member_get( List, X, List2 ),

    shuffle(List2, Shuffled, Rest).

list_member_get( [X | Rest], X, Rest ).

list_member_get( [First | Rest], X, [First | Rest2] ) :-
    list_member_get( Rest, X, Rest2 ).

结果

1 ?- shuffle([1,2,3], X, []).
X = [1, 2, 3] ;
X = [1, 3, 2] ;
X = [2, 1, 3] ;
X = [2, 3, 1] ;
X = [3, 1, 2] ;
X = [3, 2, 1] ;
false.

2 ?- shuffle([1,2,3,4], X, []).
X = [1, 2, 3, 4] ;
X = [1, 2, 4, 3] ;
X = [1, 3, 2, 4] ;
X = [1, 3, 4, 2] ;
X = [1, 4, 2, 3] ;
X = [1, 4, 3, 2] ;
X = [2, 1, 3, 4] ;
X = [2, 1, 4, 3] ;
X = [2, 3, 1, 4] ;
X = [2, 3, 4, 1] ;
X = [2, 4, 1, 3] ;
X = [2, 4, 3, 1] ;
X = [3, 1, 2, 4] ;
X = [3, 1, 4, 2] ;
X = [3, 2, 1, 4] ;
X = [3, 2, 4, 1] ;
X = [3, 4, 1, 2] ;
X = [3, 4, 2, 1] ;
X = [4, 1, 2, 3] ;
X = [4, 1, 3, 2] ;
X = [4, 2, 1, 3] ;
X = [4, 2, 3, 1] ;
X = [4, 3, 1, 2] ;
X = [4, 3, 2, 1] ;
false.