2013-10-26 72 views
2

我在Prolog中編寫的一個程序與查找從起始位置到結束位置的所有可能路徑選項有關。Prolog - 查找所有路徑選項

這是我到目前爲止有:

findAllRoutes(Start, End, Path) :- 
    findAllRoutes(Start, _, End, Path), 
    print('Successful route: '), print(Route). 

findAllRoutes(End, _, End, [End]). %route was successfully finished 

findAllRoutes(Start, Temp, End, [Start|Rest_of_List]) :- 
    path(Start, Temp), 
    findAllRoutes(Temp, _, End, Rest). 

這裏是要讀取的數據:

%path(Start, End). 
path(1, 4). %find all the possible paths from location 1 to location 4. 

%paths_in_place[[Start, End, Distance]]. 
paths_in_place[[1, 2, 250], [2, 4, 250], [1, 3, 400], [3, 4, 300]]. 

我的問題是,這是一個正確的方式來循環paths_in_place同時還保存從起始位置到結束位置途中到達的點的順序?

另外,Distance發生什麼情況時findAllRoutes被稱爲沒有提及Distance字段?在Prolog中合法傳遞Start, End, Route的參數是否合法,即使在paths_in_place的字段是Start, End, Distance

任何幫助,非常感謝。讓我知道是否需要澄清任何事情。

回答

1

序言數據是符號。你可能會以米爲單位傳遞距離,並將其視爲距離。這就是火星任務之一墜毀的原因,儘管他們使用了另一種語言。所以最終取決於你。

至於你的代碼,

findAllRoutes(Start, End, Path) :- 
    findAllRoutes(Start, _, End, Path), 
    print('Successful route: '), print(Route). 

Route?什麼Route?這是一個毫無根據的「單身」變量。 SWI Prolog警告我們這樣做。也許你的意思是Path

findAllRoutes(End, _, End, [End]). % route was successfully finished 

findAllRoutes(Start, Temp, End, [Start|Rest_of_List]) :- 
    path(Start, Temp), 
    findAllRoutes(Temp, _, End, Rest). 

再次,Rest_of_ListRest大概應該有相同的名稱(相同的邏輯變量)。

否則它看起來很好,除了它的名字:它在每個調用/回溯中找到一個路徑,而不是「AllRoutes」。名稱「AllRoutes」表示它找到所有這些名稱並將它們全部返回到它的結果參數中;不是。

然後是你的數據,它是與您的代碼同步:

%path(Start, End). 
path(1, 4). %find all the possible paths from location 1 to location 4. 

%paths_in_place[[Start, End, Distance]]. 
paths_in_place([[1, 2, 250], [2, 4, 250], [1, 3, 400], [3, 4, 300]]). 
    % ! must be in parentheses ! 

path(Start, Temp)呼叫你的代碼表明Temp是一個緊跟的後續Start。根據這些數據並非如此。另外,path/2的定義缺失。但是你可以擁有一堆事實而不是列表來定義數據。