Search code examples
ocamlfunctor

How to use a functor in OCaml


I can't find on the internet how to use the functor I've written. I will post a minimal code, if you need more contextual information tell me and I'll add, but I'm sure it's really easy to do.

I think I just don't understand what a functor is, I see things like this (I will use an analogy with Java to ilustrate my understanding since I'm new to OCaml) :

  • sig (=) Interface MyInterface
  • struct (=) Object implements MyInterface
  • functor (=) MyInterfaceBis extends MyInterface

The following example I'm about to give is stupid, it's just so I can understand the concept behind it :

module type tF = sig
type 'a t
  val create : 'a t
end

module F : tF = struct
  type 'a t = 'a list
  let create = []
end

module type tF2 = functor(F : tF) -> sig
  val foo : 'a F.t -> 'a F.t
end

module F2 : tF2 = functor(F : tF) -> struct
  let foo f = f
end

I know I can do for example :

let test = F.create

But I don't know how to use F2.

I've tried this page but it's not using my notation and I was more confused after than before.


Solution

  • F2 takes in a module with type tF and produces a module with one function foo:

    module NewF = F2 (F)
    

    For more information, see the section about functors in Real World OCaml.