Prolog:城市之间的距离

时间:2014-12-02 15:46:50

标签: prolog distance

我是Prolog的新手。我正在尝试制作一个简单的程序,使用递归结构找到城市之间的距离。当我试图找到没有直接连接的城市之间的总距离时(例如伦敦到悉尼),就会出现问题。

distance(london,newyork,3.2).
distance(london,capetown,5.8).
distance(london,rome,0.8).
distance(london,panama,4.5).
distance(panama,sydney,7.7).
distance(newyork,sanfrancisco,2.5).
distance(newyork,panama,1.9).
distance(sanfrancisco,sydney,6.2).
distance(sanfrancisco,tokyo,4.5).
distance(tokyo,calcutta,2.5).
distance(tokyo,sydney,4.1).
distance(sydney,calcutta,4.4).
distance(sydney,capetown,6.0).
distance(capetowm,rome,5.1).
distance(calcutta,cairo,2.2).
distance(cairo,rome,0.9).

connected(X,Y,Distance):-
   distance(X,Y,Distance).
connected(X,Y,Distance):-
   distance(X,Z,NewDistance),
   connected(Z,Y,NewDistance),
   Distance is Distance+NewDistance.

1 个答案:

答案 0 :(得分:1)

您可以像这样修改上一条规则:

connected(X,Y,Distance):- distance(X,Z,Distance1),
                          distance(Z,Y,Distance2),
                          SumDistance is Distance1+Distance2,
                          write(SumDistance).

这是我的结果:

1 ?- connected(london,sydney,X).
12.2
true .

路线伦敦 - >巴拿马 - >悉尼即可。我使用trace.查看其工作原理:

 2 ?- trace.
true.

[trace] 2 ?- connected(london,sydney,X)
   ....
   Redo: (7) distance(london, _G1945, _G1946) ? creep
   Exit: (7) distance(london, panama, 4.5) ? creep
   Call: (7) distance(panama, sydney, _G1950) ? creep
   Exit: (7) distance(panama, sydney, 7.7) ? creep
   Call: (7) _G1955 is 4.5+7.7 ? creep
   Exit: (7) 12.2 is 4.5+7.7 ? creep
   Call: (7) write(12.2) ? creep
12.2
   Exit: (7) write(12.2) ? creep
   Exit: (6) connected(london, sydney, _G1871) ? creep

(我删除了一些跟踪,因为它太长了。)