我需要做第3.4节的LPN实践3:写一个旅行/ 3规则,用它来搜索路线。 (link)
我目前有以下解决方案:
%% Base cases
travel(X,Y, go(X,Y)) :- byCar(X,Y).
travel(X,Y, go(X,Y)) :- byPlane(X,Y).
travel(X,Y, go(X,Y)) :- byTrain(X,Y).
%% Recursive cases
travel(X,Y, go(X,Z,G)) :- travel(X,Z,go(X,Z)), travel(Z,Y,go(Z,Y)).
根据这些规则,它会找到一个解决方案,但在交付时,我会不断收到时间限制错误,这意味着程序在确定解决方案之前会先尝试太多其他事情。有什么方法可以加快速度吗?如果是这样,我可以改进这段代码中的内容吗?
谢谢:)
答案 0 :(得分:0)
几乎就在那里,但你必须使用G
(我在这里命名为Rest
):
%% Base cases
travel(X,Y, go(X,Y)) :- byCar(X,Y).
travel(X,Y, go(X,Y)) :- byPlane(X,Y).
travel(X,Y, go(X,Y)) :- byTrain(X,Y).
%% Recursive cases
travel(X,Y, go(X,Z, Rest)):-
travel(X,Z, go(X,Z)), % you go from X to Z in one step
travel(Z,Y, Rest). % you go from Z to Y in any # of steps
示例:
travel(singapore,raglan,R).
R = go(singapore, auckland,
go(auckland, hamilton,
go(hamilton, raglan)))
从这里开始,执行4非常简单,您只需要添加how
:
%% Base cases
travel(X,Y, go(X,Y,car)) :- byCar(X,Y).
travel(X,Y, go(X,Y,plane)) :- byPlane(X,Y).
travel(X,Y, go(X,Y,train)) :- byTrain(X,Y).
%% Recursive cases
travel(X,Y, go(X,Z,Move,Rest)):-
travel(X,Z, go(X,Z,Move)),
travel(Z,Y, Rest).
示例:
travel(singapore,raglan,R).
R = go(singapore, auckland, plane,
go(auckland, hamilton, car,
go(hamilton, raglan, car)))