【发布时间】:2017-10-26 01:53:48
【问题描述】:
我似乎无法完全理解 prolog (gprolog) 的一些行为。作为一些背景,旋转应该比较两个列表并查看它们是否已移动(如下所示)。
?- rotate(1,[4,1,2,3],[1,2,3,4]).
应该返回真。但是,当提出上述问题时,prolog 似乎并不尊重规则顺序。
rotate(0,[],[],[]).
%base case
rotate(0,[],[H|T1],[H|T2]):- rotate(0,[],T1,T2).
%recurse over the remainder list (the first list from S to the end)
Prolog 会忽略下面的谓词 when
rotate(S,[H|T1],[H|T2],L):-S=:=0,rotate(0,T1,T2,L).
%recurse over the elements from S to the end of list1
从这个其他谓词回溯(直接在下面)。
rotate(S,[H|T1],L,T2):-S > 0,S1 is S - 1,rotate(S1,T1,L,[H|T2]).
%add elements 1 to S into the remainder list
rotate(S,L1,L2):-len(L1,Len),S1 is S mod Len,!,rotate(S1,L1,L2,[]).
%ensure the shift is not out of bounds, call rotate/4
%utility function because couldn't use length
len([],Ret,Ret).
len([_|T],Len,Ret):-Len1 is Len+1,len(T,Len1,Ret).
len(L,Len):-len(L,0,Len).
我通过跟踪它发现了这种行为,坦率地说,我很困惑为什么它不会回溯并命中下一个谓词,而是失败并返回 false。
我也愿意接受更好的方法来做到这一点,因为这是期中练习。
【问题讨论】:
-
也许this answer 对你来说很有趣。谓词描述任意旋转并且是真实的关系(适用于所有方向)。
标签: prolog