如何将列表的元素添加到哈希表中?

How to add the elements of a list to a hashtable?

我正在尝试使用列表向哈希表中添加元素。

我的节点类型如下:

type position = float * float
type node = position

我错误地假设并开始编写我的函数,就好像我可以应用递归构建普通列表的相同方法,但我现在不知道在哪里进行递归调用。

这是我迄今为止尝试过的方法:

let init_dist nodes source =
let hshNodes = Hashtbl.create (List.length nodes) + 5 in
let rec init_dist_aux nodes hashtable source =
  match nodes with
  | [] -> hashtable
  | x::tl > if x = source then Hashtbl.add hashtable (x,0.)
            else Hashtbl.add hashtable (x,max_float)

nodes参数是一个节点列表,source是一个节点。

我没有错误输出,因为我没有 运行 因为它无法工作。

我的目标是能够编写一个函数,允许我使用节点列表向我的 hashtbl 添加绑定。

谢谢。

你的方法看起来不错。我没有看到对 init_dist_aux 的任何递归调用,因此它将在添加第一个元素后停止。它还会产生类型错误,因为你的 match returns 的一个分支是散列 table 而另一个 returns 单元 (()).

添加递归调用应该可以解决这两个问题。

更新

你现在有这个:

if x = source then
    Hashtbl.add hashtable (x,0.)
else
    Hashtbl.add hashtable (x,max_float)

你想要的是这个:

if x = source then
    Hashtbl.add hashtable x 0.
else
    Hashtbl.add hashtable x max_float;
init_dist_aux tl hashtable source

通过此更改,您的 init_dist_aux 函数已经 returns 一个散列 table。没有什么特别的事情可以做到这一点。

但请注意,我在任何地方都看不到对 init_dist_aux 的调用。您肯定需要调用它才能正常工作:-)

(作为旁注,如果 init_dist_aux 的代码对您来说不是很明显,您可能需要花更多时间考虑递归。只是一个粗略的观察。)