在 Ocaml 中打印哈希映射的内容

Print content of a hash map in Ocaml

在 Ocaml 中打印散列内容 table 的最简单方法是什么?我是 Ocaml 的新手,到目前为止我所看到的一切看起来都非常复杂。 举例来说,如果我们生成一个简单的散列 table,如下所示:

# let ht = Hashtbl.create 100;;
# Hashtbl.add ht "x" "a";
  Hashtbl.add ht "x" "b";
  Hashtbl.add ht "y" "c";;

我想这样打印:

# print_hash ht;;

然后得到如下结果:

x:a,b

y: c

我想我必须使用 Marshal 模块,但我真的不知道具体怎么做 因为使用 to_string 选项,结果不可读。

一个简单的技巧在于使用 Hashtbl.iter :

 Hashtbl.iter (fun x y -> Printf.printf "%s -> %s\n" x y) ht;;

给定的函数有第一个参数需要 2 个参数,即键和值。

这有效,假设键和值是字符串:

# let open BatInnerIO in
  BatHashtbl.print write_string write_string stdout ht;;

这会打印出格式相当整齐的字符串:

{
Key1: Value1,
Key2: Value2
}

如果你的键and/or值类型不是字符串,你可以使用BatInnerIO的其他打印机,比如write_i64写下一个int64,等等上。

也可以打印到 stderr