Loading ...
Sorry, an error occurred while loading the content.

13070I need help deciphering Martin's hash table code

Expand Messages
  • Jean Saint-Remy
    Jan 1, 2012
    • 0 Attachment
      Hi Everyone,


      Happy New Year 2012!

      I have been trying to decipher hash table code of Martin Jambon. The code can be found at http://martin.jambon.free.fr/hashtbl2.ml.html.

      type ('a, 'b) t = ('a, 'b list ref) Hashtbl.t

      let add tbl key data =
      let r =
      try Hashtbl.find tbl key
      with Not_found ->
      let r = ref [] in
      Hashtbl.add tbl key r;
      r in
      r := data :: !r


      The type definition on the left side of the "=" sign is the same as in the OCaml Hashtbl reference.
      The right side of the "=" sign indicates that of any two types that are a hash, the second is bound as a list reference. The problem I am having is understanding the segment "let r =" in the add function. When adding a key to the hash table, first we check to see if it already exists in the table, if it is not found, we treat it as a list reference, assigning the "new" key to the table, and consing the value part into the ref list (here the k,v pairs are denoted by variables 'key' and 'data' respectively).

      Why are we assigning the "try...with" block to the variable 'r'? Do we need to emit some kind of a message that the key already exists in the hash table, or are we simply going to overwrite the value? What about the second 'let r = ref [] in", is it shadowing the variable 'r'? Meaning, the "try..with' block is no longer valid, instead 'r' is now a reference list, the table takes the "key" and "data" is inserted at the head of the list, and the content of 'r' is the tail of the list.

      I have faith that this is the most efficient add function as far as hash tables are concerned, but it is the first time that I come across a dangling variable "r in" in a statement. This seems to me very strange. Could we omit the "try...with" block and simply add the k,v pair to the hash table directly? In other words, skip to the second "let r = ref [] in" and assign the k,v pairs to the table?

      Any insight will be much appreciated.

      With kind regards,

      Jean
    • Show all 3 messages in this topic