[英]The Farmer's puzzle - recursive rules and accumulators break my approach
几个小时前,我开始学习Prolog,但对于实施Farmer问题的求解器我还是一无所获。 我知道网络上有很多示例,但是出于学习的目的,我想了解我的代码为什么不起作用,该方法是否有效以及导致这种问题的正确方法是什么? 。
参见下面的代码。 我所做的是:
到目前为止,我已经实现了:
我认为我已经找到问题了 ,如果我错了 ,请纠正我:如果解决方案需要3个以上的步骤,则最后一个行程规则至少计算两次,并且在第一次递归执行后, PreviousStates累加器不为空。 什么时候统一? 探索的答案not(member(Next,PreviousStates))然后失败,因为Next状态包含的变量将与PreviousStates列表开头的变量匹配。
因此,我的问题是:
在此先感谢您的帮助!
%Define what are the unsafe states for the Farmer, Goat, Cabbage and Wolf
unsafeState(F,G,C,W) :-
(C=G, not(C=F));
(G=W, not(G=F)).
safeState(F,G,C,W) :- not(unsafeState(F,G,C,W)).
%Define what are the valid and safe transitions
isSafeTransition(state(F,F,C,W),state(Fend,Fend,C,W)) :- safeState(F,F,C,W), safeState(Fend,Fend,C,W).
isSafeTransition(state(F,G,F,W),state(Fend,G,Fend,W)) :- safeState(F,G,F,W), safeState(Fend,G,Fend,W).
isSafeTransition(state(F,G,C,F),state(Fend,G,C,Fend)) :- safeState(F,G,C,F), safeState(Fend,G,C,Fend).
isSafeTransition(state(F,G,C,W),state(Fend,G,C,W)) :- safeState(F,G,C,W), safeState(Fend,G,C,W).
% Initial matching rule
trip(A,B,Path):- trip(A,B,Path, []).
% Finishing rule
trip(CurrentState, EndState,Path, _):-
[CurrentState| [EndState|[]] ] = Path,
isSafeTransition(CurrentState, EndState).
trip(CurrentState,EndState,Path, PreviousStates):-
[CurrentState|[Next|Tail]] = Path,
not(member(Next,PreviousStates)),
isSafeTransition(CurrentState,Next),
trip(Next,EndState, [Next|Tail], [CurrentState|PreviousStates]).
我自己发现了问题,我发布了解释以防万一。
问题在于没有任何规则限制头寸的可能值 。 基本上我忘了将可能的值限制为n或s ...
解决查询时,变量的潜在值是无限的。 这就是为什么包含变量的状态存储在累加器中并与下一个状态匹配的原因。
为了解决该问题,我添加了两个事实 ,这些事实定义了头寸的有效值 ,并修改了控制状态是否有效的规则以包括这些值。
在固定程序下找到:
% Define the valid sides for any participant
side(n).
side(s).
% Define what are the valid states for the Farmer, Goat, Cabbage and Wolf
unsafeState(F,G,C,W) :-
(C=G, not(C=F));
(G=W, not(G=F)).
validState(F,G,C,W) :-
side(F),side(G),side(C),side(W),
not(unsafeState(F,G,C,W)).
%Define what are the valid and safe transitions
isSafeTransition(state(F,F,C,W),state(Fend,Fend,C,W)) :-
validState(F,F,C,W), validState(Fend,Fend,C,W).
isSafeTransition(state(F,G,F,W),state(Fend,G,Fend,W)) :-
validState(F,G,F,W), validState(Fend,G,Fend,W).
isSafeTransition(state(F,G,C,F),state(Fend,G,C,Fend)) :-
validState(F,G,C,F), validState(Fend,G,C,Fend).
isSafeTransition(state(F,G,C,W),state(Fend,G,C,W)) :-
validState(F,G,C,W), validState(Fend,G,C,W).
% Initial matching rule
trip(A,B,Path):- trip(A,B,Path, []).
% Finishing rule
trip(CurrentState, EndState,Path, _):-
[CurrentState| [EndState|[]] ] = Path,
isSafeTransition(CurrentState, EndState).
trip(CurrentState,EndState,Path, PreviousStates):-
[CurrentState|[Next|Tail]] = Path,
not(member(CurrentState,PreviousStates)),
isSafeTransition(CurrentState,Next),
trip(Next,EndState, [Next|Tail], [CurrentState|PreviousStates]).
我仍然是Prolog的新手,所以如果有人可以为任何更正做贡献,请这样做!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.