Custom type; key for Core.Hashtbl.create

Say we create a custom type:

type t = A of int | B of string
  1. What do we need to implement in order to use it as the Key for a Core.Hashtbl ?

  2. Is there some ppx that will auto derive this for us ?


1 Like

This can get slightly complicated as there are a few different ways of working with hashtables in Core. Some of these differences are due to choices about which specific operations you want to support (for example, do you plan on serializing the hashtable with bin_prot?). And some differences reflect historical differences in approach between Base and Core, both of which approaches are supported in Core currently.

But, assuming you want to use Core.Hashtbl.create, you just need compare, sexp_of_t, and hash, i.e. the interface documented here.

To get these via ppx, you can do [@@deriving hash, compare, sexp_of], which depends on ppx_hash, ppx_compare, and ppx_sexp_conv (or just use ppx_jane to pick up most of the Jane Street ppxes).


If you are asking for Hashtbl you may also be interested in using your custom types as keys for Map and Set as well.

Here’s an example of setting your type up so you can use it with either a Hashtbl, Map, or Set. It uses the Comparator.Make functor so you don’t have to write the boilerplate yourself. (note: you will see this inner-module-T pattern used a lot in base/core, so if you plan to use them, it is a good pattern to be familiar with.)

open! Base

module Foo = struct
  module T = struct
    type t = int [@@deriving compare, hash, sexp_of]

  include T
  include Comparator.Make (T)

  (* Lot's of stuff. *)

let foo_ht = Hashtbl.create (module Foo)
let foo_map = Map.empty (module Foo)
let foo_set = Set.empty (module Foo)

You can see more info here: motivation for ppx_hash, and this section of Real World OCaml.

(By the way, let me just callback to your previous question about the point of deriving sexp. I mentioned there about certain of Base/Core functors required sexp, well, above is one example of that!)