为什么在HashTable中找不到我的条目

  • 本文关键字:找不到 HashTable ocaml
  • 更新时间 :
  • 英文 :


我有以下代码:

let to_permutation pairs max_el =
let tbl = Hashtbl.create 100 in
let rec aux i collector = 
if i > max_el then collector
else 
match Hashtbl.find_opt tbl i with
None ->   
ignore (Printf.printf "NOT found n");
Hashtbl.add tbl i 1;
aux (i + 1) (List.append (List.hd collector) [List.assoc i pairs] :: List.tl collector)           
| Some _ ->
ignore (Printf.printf "Foundn");
aux (i + 1) (List.append [[]] collector)  
in
aux 1 [[]];;

它应该做的是:当我给函数一个对的列表时,我希望它生成映射整数的循环(基于对(

示例:to_permutation [(1, 6); (2, 3); (3, 5); (4, 1); (5, 2); (6, 4)] 6;;应该返回类似于[[1; 6; 4]; [2; 3; 5]];的内容。

然而,我甚至还没有接近这一点,因为检查我是否已经访问了一个元素(从而检测到一个循环(的查找失败了。程序的输出:

to_permutation [(1, 6); (2, 3); (3, 5); (4, 1); (5, 2); (6, 4)] 6;;
NOT found 
NOT found 
NOT found 
NOT found 
NOT found 
NOT found 
- : int list list = [[6; 3; 5; 1; 2; 4]]

尽管我插入到哈希表中,但它从未找到元素。我做错了什么?

通过对aux i的调用,可以保持不变,即表tbl只包含严格低于i的键。因此,find_opt tbl i总是返回None,并且在调用aux (i+1)之前向tbl添加i密钥,以保持前面所述的不变量。

最新更新