Signature file using ppx and functors


#1

Hi,

I am new to OCaml and am writing the following implementation in a .ml file, using Core and ppx_jane:

open Core

module T = struct
  type 'a t =
    | Case1
    | Case2 of 'a
  [@@deriving compare, sexp]
end

include T

include Comparable.Make(T)

My question is what the .mli signature file would look like.

Thanks!


#2

You can use the @@deriving features from ppx_jane in the signature too:

module T : sig
  type 'a t =
  | Case1
  | Case2 of 'a
  [@@deriving compare, sexp]
end

The above gets rewritten to something like:

module T : sig
  type 'a t =
  | Case1
  | Case2 of 'a

  val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int

  val sexp_of_t : ('a -> Sexp.t) -> 'a t -> Sexp.t
  val t_of_sexp : (Sexp.t -> 'a) -> Sexp.t -> 'a t
end

I don’t think Comparable can be used with polymorphic types, however. If it could, the rest of the signature might look like:

include T
include Comparable.S1

#3

Almost. I think that last declaration should look like:

type 'a t
include Comparable.S1 with type 'a t := 'a t

#4

Is there a way in the signature file to link T.t with t?

That is, I have the following files:

my_module.ml:

module T = struct
  type 'a t =
    | Case1
    | Case2 of 'a
  [@@deriving compare, sexp]
end

include T

let my_func =
  function
  | Case1 -> 1
  | Case2 _ -> 2

my_module.mli:

module T : sig
  type 'a t =
    | Case1
    | Case2 of 'a
  [@@deriving compare, sexp]
end

type 'a t

val my_func : 'a t -> int

my_test.ml:

open My_module

let () =
  let x = Case2 "a" in
  let i = my_func x in
  Printf.printf "%d\n" i

jbuild:

(library
 ((name my_module)
  (modules my_module)
  (preprocess (pps (ppx_jane)))))

(executable
 ((name my_test)
  (modules (my_test))
  (libraries (my_module))))

When I run jbuilder build my_test.exe I get the following:

File "my_test.ml", line 4, characters 10-15:
Error: Unbound constructor Case2

However, when my_module.mli looks like the following, there is no such error:

type 'a t =
  | Case1
  | Case2 of 'a

val my_func : 'a t -> int

#6

How about replacing type 'a t in the .mli with include module type of T?