简体   繁体   English

如何使用列表构建地图?

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

I have a node type like the following :我有一个如下所示的节点类型:

type position = float * float
type node = position

I created those modules for the Map :我为 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)

I have written this function to add elements to my map.我编写了这个函数来向我的地图添加元素。

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

The output was :输出是:

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

I tried this :我试过这个:

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

However init_dist has type unit, so I was unable to create the Map.但是 init_dist 的类型是 unit,所以我无法创建 Map。

My goal is to be able to use this function to build a map.我的目标是能够使用此功能来构建地图。

The error lays in the code below :错误在于下面的代码:

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

Around the 2 pieces of code :围绕 2 段代码:

map = DistMap.add...

This is a comparison (and so a boolean) not an assignement as you might wish to implement.这是一个比较(因此是一个布尔值),而不是您可能希望实现的赋值。 You have to first evaluate map via let and then process init_dist_aux with new map.您必须首先map via let 评估map via ,然后使用新地图处理 init_dist_aux 。 Or, since the only difference is the 2nd value (0. or max_float), you can first evaluate this second argument, then process the whole thing as below:或者,由于唯一的区别是第二个值(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