ocaml hashtbl删除函数
Hashtbl remove如何恢复以前的绑定ocaml hashtbl删除函数,ocaml,Ocaml,Hashtbl remove如何恢复以前的绑定 Hashtbl.add t key1 Hashtbl.remove t key1 Hashtbl.remove t key1 => This should do anything but not restore the key1 ! 无论如何,为什么我可以删除一些东西,确保它被删除之前,然后正确的流程应遵循 如果您使用Hashtbl.replace而不是Hashtbl.add您将替换t中键的当前绑定。因此函数Hashtbl.rem
Hashtbl.add t key1
Hashtbl.remove t key1
Hashtbl.remove t key1 => This should do anything but not restore the key1 !
无论如何,为什么我可以删除一些东西,确保它被删除之前,然后正确的流程应遵循
如果您使用
Hashtbl.replace
而不是Hashtbl.add
您将替换t
中键的当前绑定。因此函数Hashtbl.remove
不会还原任何内容
您还可以编写自己的删除函数:
let remove tbl key =
if Hashtbl.mem tbl key then Hashtbl.remove tbl key
else raise Nothing_to_remove_in_the_hashtbl
Hashtbl.replace t key1 value;;
remove t key1;;
remove t key1;; (* raise Nothing_to_remove_in_the_hashtbl *)
Hashtbl
有两种合法的使用模式:始终使用Hashtbl.replace
,这确保每个键在表中只有一个绑定,或者使用表作为多重映射(每个键指向一个值列表),使用Hasthbl.add
、Hashtbl.find
和Hashtbl.find\u all
请确保您了解您感兴趣的使用模式。如果不想保留旧绑定(这可能会导致性能问题、内存泄漏和堆栈溢出),那么向同一个键添加多个绑定是没有意义的;在这种情况下,您应该使用Hashtbl.replace
而不是Hashtbl.add
,而Hashtbl.remove
将完全满足您的期望
如果要将哈希表用作多重映射,并且需要一个删除键的所有绑定的函数,则可以在yourslef(未测试的代码)中实现该函数:
编辑:我刚刚了解到,阅读您(难以理解)问题的另一种方式是“如何确保表中有要删除的键,而不是在调用
remove
时静默地什么也不做?”。cago为此提供了一个代码片段,本质上,您可以使用Hashtbl.mem
检查绑定是否存在,如果您认为它应该存在。对于Hashtbl.replace,Hashtbl.remove在删除未找到的绑定时会崩溃key@blackmath你说的“撞车”是什么意思?我刚刚测试过,正如文档所描述的,删除一个不存在的密钥不会产生任何效果(没有错误)。
let rec remove_all tbl key =
if Hashtbl.mem tbl key then begin
Hashtbl.remove tbl key;
remove_all tbl key
end