I essentially want to do the following:
open Core;;
module Value =
struct
type t =
| Int of int
| Object of t Map.M(String).t
[@@deriving compare, hash, sexp_of]
;;
end
;;
let v : (Value.t, int) Hashtbl.t = Hashtbl.create (module Value)
Closest I got was by hunting down the proper type definitions and implementing everything myself in a recursive module like so:
open Core;;
module rec Value:
sig
module K:
sig
type t = Value.t Map.M(String).t ;;
val compare: t -> t -> int ;;
val sexp_of_t: t -> Sexp.t ;;
val hash_fold_t: Hash.state -> t -> Hash.state ;;
end
;;
type t =
| Int of int
| Object of K.t
;;
val compare: t -> t -> int ;;
val sexp_of_t: t -> Sexp.t ;;
val hash_fold_t: Hash.state -> t -> Hash.state ;;
val hash: t -> Hash.hash_value ;;
end = struct
module K = struct
type t = Value.t Map.M(String).t ;;
let compare a b = Map.compare_direct Value.compare a b
;;
let sexp_of_t a = Sexp.List (
Map.fold a ~init:[] ~f:(fun ~key:k ~data:d l ->
(Sexp.Atom k) :: (Value.sexp_of_t d) :: l))
;;
let hash_fold_t (state: Hash.state) (v: t): Hash.state =
Map.fold v ~init:(hash_fold_int state (Map.length v)) ~f:(fun ~key:k ~data:d state ->
Value.hash_fold_t (hash_fold_string state k) d)
;;
end
;;
type t =
| Int of int
| Object of K.t
[@@deriving compare, sexp_of, hash]
;;
end
;;
let v : (Value.t, int) Hashtbl.t = Hashtbl.create (module Value)
Is there a better way? I saw Base.Map
has a hash_fold_direct function but I could not figure out how to use it. Also, the fact that at the bottom of that page there’s sexp_of_m__t
, compare_m__t
and hash_fold_m__t
which look like the functions @@deriving
is asking for but I cannot figure out how to reach them is taunting me.
I tried using [@@deriving_inline compare, hash, sexp_of]
but it seemed like it wasn’t doing anything at all.
Btw I’m completely new to OCaml so any comments are welcome.