Converting hash table to list of pairs (key,value) in OCaml

試著忘記壹切 提交于 2019-12-23 07:33:36

问题


Is there a way of converting a hash table into a list of (key,pair) values in OCaml?

I'm aware that, given a hash table ht we can do

BatList.of_enum (BatHashtbl.enum ht)

using the batteries library. This would convert the table to an enumeration and then convert the enum to a list. But I'm looking for a solution that doesn't use the Batteries Library. In the standard OCaml Hashtbl Module there doesn't seem to be a way of extracting the pairs as a list or a way of combining its functions to achieve this purpose. Any suggestions?


回答1:


In the standard OCaml Hashtbl Module there doesn't seem to be ...

Of couse there is!

val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c

So, use:

fun h -> Hashtbl.fold (fun k v acc -> (k, v) :: acc) h []


来源:https://stackoverflow.com/questions/4059978/converting-hash-table-to-list-of-pairs-key-value-in-ocaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!