繁体   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