[英]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.