1
other_bank(e,w).
other_bank(w,e).
% farmer,wolf,goat,cabbage
move([X,X,Goat,Cabbage],wolf,[Y,Y,Goat,Cabbage]) :- other_bank(X,Y).
move([X,Wolf,X,Cabbage],goat,[Y,wolf,Y,Cabbage]) :- other_bank(X,Y).
move([X,Wolf,Goat,X],cabbage,[Y,Wolf,Goat,Y]) :- other_bank(X,Y).
move([X,Wolf,Goat,Cabbage],nothing,[Y,Wolf,Goat,Cabbage]):-other_bank(X,Y).

safety_check(X,X,_).
safety_check(X,_,X).
safe_status([Man,Wolf,Goat,Cabbage]):-
    safety_check(Man,Goat,Wolf),
    safety_check(Man,Goat,Cabbage).
solution([e,e,e,e],[]).
solution(Config,[Move|OtherMoves]):-
    move(Config,Move,NextConfig),
    safe_status(NextConfig),
    solution(NextConfig,OtherMoves).

% length(X,7),solution([w,w,w,w],X).

在 GNU Prolog 中加载 .pl 文件时出现编译错误

农夫-狼-山羊-白菜问题

4

1 回答 1

1

你快到了!用小写的 wolf 拼写时是一个常数(大写的 Wolf 是一个变量)。

other_bank(e,w).
other_bank(w,e).
% farmer,wolf,goat,cabbage
move([X,X,Goat,Cabbage],wolf,[Y,Y,Goat,Cabbage]) :- other_bank(X,Y).
move([X,Wolf,X,Cabbage],goat,[Y,Wolf,Y,Cabbage]) :- other_bank(X,Y).
move([X,Wolf,Goat,X],cabbage,[Y,Wolf,Goat,Y]) :- other_bank(X,Y).
move([X,Wolf,Goat,Cabbage],nothing,[Y,Wolf,Goat,Cabbage]):-other_bank(X,Y).

safety_check(X,X,_).
safety_check(X,_,X).
safe_status([Man,Wolf,Goat,Cabbage]):-
    safety_check(Man,Goat,Wolf),
    safety_check(Man,Goat,Cabbage).
    
solution([e,e,e,e],[]).
solution(Config,[Move|OtherMoves]):-
    move(Config,Move,NextConfig),
    safe_status(NextConfig),
    solution(NextConfig,OtherMoves).

?- length(X,7),solution([w,w,w,w],X).
X = [goat,nothing,wolf,goat,cabbage,nothing,goat]
于 2021-02-03T07:56:00.187 回答