I’m playing with first-class modules in OCaml, and since I’m still a noob, I stumbled upon a compiler error I can’t resolve on my own. So I’d appreciate any help!
I want to make a simple module for a semigroup like this one:
module type Semigroup = sig
type t
val append : t -> t -> t
end
This works perfectly, and I can even create some trivial instances:
module Int_semigroup : Semigroup = struct
type t = int
let append = (+)
end
However, the following doesn’t work when I’m creating a semigroup module for a list:
module List_semigroup : Semigroup = struct
type t = 'a t
let append = (@)
end
The error message is the following (and it makes sense so far):
Error: The type constructor t expects 0 argument(s),
but is here applied to 1 argument(s)
I found the following way to define such modules for types that should be parametrised by variables (I don’t know if it’s idiomatic in OCaml though). The List_semigroup
just needs to be a functor that takes a module with just a type inside:
module List_semigroup (T: sig type t end) : Semigroup = struct
type t = T.t list
let append = (@)
end
This compiles. However, now I’m getting problems using this module. The following code doesn’t compile:
module L = List_semigroup(struct type t = int end)
let example =
let l1 = [3; 1; 2] in
let l2 = [0, 1, 2] in
L.append l1 l2
and the error is (highlighting l1
inside `L.append l1 l2):
Error: This expression has type int list but an expression was expected of type L.t
Could someone explain how to resolve this error and make my example compile?