2017-06-18 15 views
0

我要比较两个哈希表的平等:OCaml的 - 两个哈希表的平等和函数嵌套标记参数

open Core.Std 

let hashtables_equal (x_tbl: ('a, 'b) Hashtbl.t) (y_tbl: ('a, 'b) Hashtbl.t) : bool = 
    (Hashtbl.length x_tbl = Hashtbl.length y_tbl) 
    && Hashtbl.for_alli x_tbl ~f:(fun ~key ~data -> Hashtbl.existsi y_tbl ~f:(fun ~k ~d -> k = key && d = data)) 

for_alli功能fexistsi有两个标记参数~key~data

上面的代码由于使用了不正确的标签而无法编译。但是,我想在嵌套函数中引用~key~data标记的参数。

我该怎么做?

回答

0

您可以给一个带标签参数的本地名称,您不需要使用标签本身作为名称。

let hashtables_equal x_tbl y_tbl = 
    Hashtbl.length x_tbl = Hashtbl.length y_tbl && 
    Hashtbl.for_alli x_tbl ~f: (fun ~key ~data -> 
     Hashtbl.existsi y_tbl ~f:(fun ~key:k ~data:d -> 
      k = key && d = data)) 

对于它的价值,似乎是在核心功能,对平等的比较哈希表:在这种情况下

let hashtables_equal x_tbl y_tbl = Hashtbl.equal x_tbl y_tbl (=) 

最后一个参数,(=),是在情况比较元素通常的比较不是你想要的。 (因为它不会是散列表,作为一个例子。)