[英]How to build a list using a Map?
首先,我有這些類型:
type position = float * float
type node = position
為了構建我的地圖,我編寫了這些模塊:
module MyMap =
struct
type t = Graph.node
let compare (a1,b1) (a2,b2) =
if a1 > a2 then 1
else if a1 < a2 then -1
else if b1 > b2 then 1
else if b1 < b2 then -1
else 0
end
module DistMap = Map.Make(MyMap)
在我的情況下,我將有一個previousMap
具有類型val previousMap : (float * float) DistMap.t = <abstr>
它包含節點作為鍵和值。 假設它是這樣構建的:
DistMap.bindings prevMap;;
- : (node * (float * float)) list =
[((1., 1.), (2., 2.));
((2., 2.), (3., 3.));
((3., 3.), (4., 4.));
((4., 4.), (5., 5.))]
這意味着 (2.,2.) 是圖中 (1.,1.) 的前驅節點。
我的目標是構建表示從source
節點到target
節點的路徑的列表。
例如,如果我有:
let build_path prevMap source target
使用previousMap
的預期輸出將是一個node (or float * float) list
如下所示:
build_path previousMap (1.,1.) (5.,5.) -> [(1.,1.);(2.,2.);(3.,3.);(4.,4.);(5.,5.)]
到目前為止,我的嘗試包括嘗試在previousMap
上使用fold
和iter
函數,但它們沒有定論。
更新 :
這是我認為可能接近我想要實現的嘗試:
let build_list map source target =
let rec build_aux acc map source x =
if ((DistMap.find x map)) = source then source::acc
else build_aux (DistMap.find x map)::acc source (DistMap.find x map)
in build_aux [] map source target
但是我得到這個錯誤輸出:
356 | else build_aux (DistMap.find x map)::acc source (DistMap.find x map)
^^^^^^^^^^^^^^^^^^^^
Error: This expression has type 'a but an expression was expected of type
'a list
The type variable 'a occurs inside 'a list
更新2:
問題已解決,但功能未按預期運行。 基本上這是我想要實現的偽代碼:
我怎樣才能繼續建立這樣的清單?
謝謝。
fold
和iter
的問題在於它們按照它們自己確定的順序處理節點。 本質上,順序是基於地圖的形狀,由鍵決定。 您希望按照地圖中的值確定的順序處理地圖的節點。
我很確定繼續進行的唯一方法是編寫自己的特殊用途遞歸函數。
更新
在最新的代碼中,你有這個表達式:
build_aux (DistMap.find x map)::acc source (DistMap.find x map)
OCaml 中將函數參數綁定到函數的運算符優先級非常嚴格,因此解析如下:
(build_aux (DistMap.find x map)) :: (acc source (DistMap.find x map))
您需要在此子表達式周圍加上括號:
((DistMap.find x map)::acc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.