首页 > 解决方案 > 如何将列表的元素添加到哈希表?

问题描述

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

我有如下节点类型:

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。

谢谢。

标签: listocamlhashtable

解决方案


你的方法似乎很好。我没有看到任何对 的递归调用init_dist_aux,所以它会在添加第一个元素后停止。它还会产生类型错误,因为您的一个分支match返回一个哈希表,另一个返回单元 ( ())。

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

更新

你现在有这个:

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函数已经返回一个哈希表。没有什么特别的事情可以做到这一点。

但请注意,我没有看到init_dist_aux任何地方的呼叫。你肯定需要调用它才能让事情正常工作:-)

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


推荐阅读