簡體   English   中英

如何使用列表構建地圖?

[英]How to build a Map using a list?

我有一個如下所示的節點類型:

type position = float * float
type node = position

我為 Map 創建了這些模塊:

module MyMap =
  struct
  type t = 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)

我編寫了這個函數來向我的地圖添加元素。

let init_dist nodes source =
  let testMap = DistMap.empty in
  let rec init_dist_aux nodes map source =
    match nodes with
    | [] -> map
    | x::tl -> if x = source then map = DistMap.add x 0. map else map = DistMap.add x max_float map;
    init_dist_aux tl map source
  in init_dist_aux nodes testMap source

輸出是:

Characters 160-186:
Warning 10: this expression should have type unit.
val init_dist : node list -> node -> float DistMap.t = <fun>

我試過這個:

let initMap = init_dist nodes (4.67521849144109414,6.85329046476252568);;

但是 init_dist 的類型是 unit,所以我無法創建 Map。

我的目標是能夠使用此功能來構建地圖。

錯誤在於下面的代碼:

match nodes with
| [] -> map
| x::tl -> if x = source then map = DistMap.add x 0. map else map = DistMap.add x max_float map;
init_dist_aux tl map source

圍繞 2 段代碼:

map = DistMap.add...

這是一個比較(因此是一個布爾值),而不是您可能希望實現的賦值。 您必須首先map via let 評估map via ,然后使用新地圖處理 init_dist_aux 。 或者,由於唯一的區別是第二個值(0. 或 max_float),您可以先評估第二個參數,然后按如下方式處理整個事情:

match nodes with
| [] -> map
| x::tl -> let v = if (x = source) 
               then        0. 
               else max_float 
           in 
               init_dist_aux tl (Dist.add x v map) source

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM