list - 如何将列表的元素添加到哈希表?
问题描述
我正在尝试使用列表将元素添加到我的哈希表中。
我有如下节点类型:
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
返回一个哈希表,另一个返回单元 ( ()
)。
添加递归调用应该可以解决这两个问题。
更新
你现在有这个:
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
您来说不是很明显,您可能需要花更多时间考虑递归。只是一个谦虚的观察。)
推荐阅读
- java - java.util.NoSuchElementException:不存在值
- azure - 使用“应用程序”权限将事件添加到 O365 组日历
- asp.net-core - AuthenticationTicket SetResources/SetProperties 我该如何使用它们?
- python - Airflow 如何从 python 运算符创建数据流作业?
- python - 在充满文件的目录中递归搜索特定字符串
- c# - 用户“XX”登录失败
- laravel - Ioredis 与 Laradock redis 容器连接超时
- selenium-webdriver - 我很难为下面的代码构造 x 路径
- android - 没有从活动中获得片段的价值
- ruby-on-rails - 为什么我的辅助数据库不能在生产中连接?